Java Reference
In-Depth Information
structural patterns
Structural patterns concern how classes and objects are structured, mainly how inheritance and
interfaces should be applied to design, or redesign, object‐oriented architectures in useful ways.
Most of these patterns involve wrapping of some kind, i.e., creating classes that contain instances
of other classes or subclass other classes. Such patterns often show up in cases when code is being
refactored or when complex classes are wrapped in simpler ones.
The adapter, bridge, decorator, façade, and composite patterns are discussed here. The type pattern,
which is not explicitly mentioned in the Gang of Four book, but deals with an interesting and useful
aspect of Object-Oriented Programming, is also included here as an explicit pattern. The structural
proxy and flyweight patterns are not addressed, as their use cases are less relevant for beginners (feel
free to look them up, however).
adapter Pattern
The goal of the adapter pattern is to make classes with incompatible interfaces work together, as
illustrated here. Imagine a world with two printer companies. One is called Ink4Ever and has a class
somewhere in its driver code that looks like this:
public class InkjetPrinter {
public void print(Document d, int nrCopies) {
// Print code here
}
public void printDuplicate(Document d, int nrCopies) {
// Print code here
}
}
The second printer company, called MajorLaser, has a driver class like this:
public class LaserPrinter {
public void print(Document d, boolean printDuplicate) {
// Print code here
}
}
After many years of fierce competition, the two companies merge to form a new entity, called
Ink&Laser. The programmers start working on exciting new printer software, with the final task of
creating a unified driver that can work with laser and inkjet printers.
The team decides it would be best to use the following single method throughout the codebase:
public void print(Document d, int nrCopies, boolean printDuplicate)
The question now is how to implement this approach so that it works with the inkjet and laser
printer drivers, as they do not agree on their method signatures. One of the programmers suggests
just merging the two legacy printers into a new, unified driver, like so:
public class UnifiedPrinter {
public void print(Document d, int nrCopies, boolean printDuplicate) {
 
Search WWH ::




Custom Search