Java Reference
In-Depth Information
if (isLaser()) {
for (int copy = 1; copy <= nrCopies; copy++)
printLaser(d, printDuplicate);
} else {
if (printDuplicate)
printInkjetDuplicate(d, nrCopies);
else
printInkjet(d, nrCopies);
}
}
public void printInkjet(Document d, int nrCopies) {
// Print code here
}
public void printInkjetDuplicate(Document d, int nrCopies) {
// Print code here
}
public void printLaser(Document d, boolean printDuplicate) {
// Print code here
}
public boolean isLaser() {
// Figure out whether this is a laser printer or not
return true;
}
}
At first, this seems like a smart idea, but the project manager disapproves. “This won't do,” he
tells his team, “It is far too hard to merge the two classes into a single one, what with the similarly
named variables and all. Even more important, what are we going to do once we start supporting a
third type of printer? This is not the object‐oriented way to do things.” The programmers are rub-
bing their heads. What would be the right way to implement this correctly? Starting purely from an
object‐oriented perspective, a natural place to start is by defining a Printer interface containing the
method signature that all printer drivers should support:
public interface Printer {
public void print(Document d, int nrCopies, boolean printDuplicate);
}
Next, InkjetPrinter and LaserPrinter can be renamed LegacyInkjetPrinter and
LegacyLaserPrinter , and two new classes can be defined:
public class LaserPrinter implements Printer {
public LegacyLaserPrinter printer = new LegacyLaserPrinter();
@Override
public void print(Document d, int nrCopies, boolean printDuplicate) {
for (int copy = 1; copy <= nrCopies; copy++)
printer.print(d, printDuplicate);
}
Search WWH ::




Custom Search