Java Reference
In-Depth Information
}
public class InkjetPrinter implements Printer {
public LegacyInkjetPrinter printer = new LegacyInkjetPrinter();
@Override
public void print(Document d, int nrCopies, boolean printDuplicate) {
if (printDuplicate)
printer.print(d, nrCopies);
else
printer.print(d, nrCopies);
}
}
Note how LegacyInkjetPrinter and LegacyLaserPrinter are now contained as instances in the
adapter classes InkjetPrinter and LaserPrinter . This is exactly what this pattern is about: wrap-
ping instances of incompatible classes in adapters. Note that the Printer interface can now be used
everywhere in the code to pass around printer objects.
NOTe Of course, you still need to decide whether to use an InkjetPrinter
or LaserPrinter class at construction. Since this is a creation issue, you might
want to use the factory pattern to construct the appropriate object, based on
the hardware configuration detected on the computer.
Finally, note that there is another variant of this pattern where a new class is created that extends all
original legacy classes. As you've seen before, multiple inheritance is not possible in Java, although
one way to apply this pattern would be if all legacy classes also have associated interfaces. The new
class can then implement all these interfaces.
Bridge Pattern
Next up is the bridge pattern. This pattern is sometimes confused with the adapter pattern, the
reason being that the bridge pattern uses the adapter pattern, but goes a step further. It not only
keeps flexibility in the implementation (e.g., to choose which printer class to use, all implementing
the interface Printer ), but also allows greater abstraction. Say you have the Printer interface and
InkjetPrinter and LaserPrinter as implementing classes, perhaps still using the legacy classes.
The key point to remember is that you have an interface and different implementations of this
interface.
Now, an additional abstraction is added on top of the implementations, a class that will sit between
the client code and the implementations. That is a bridging class. In the example, this class might be
called AbstractPrintSpooler :
public abstract class AbstractPrintSpooler {
private Printer printer;
public AbstractPrintSpooler(Printer printer) {
this.printer = printer;
 
Search WWH ::




Custom Search