The Principle of Encapsulating Variation

Several people have remarked about a certain similarity in all of the designs they have seen me create: my inheritance hierarchies rarely go more than two levels of classes deep. Those that do typically fit into a design pattern structure that requires two levels as a base for the derived classes (the Decorator pattern, discussed in Chapter 15, is an example that uses three levels).

The reason for this is that one of my design goals is never to have a class contain two things that are varying that are somehow coupled to each other. The patterns I have described so far do illustrate different ways of encapsulating variation effectively.

The Bridge pattern is an excellent example of encapsulated variation. The implementations present in the Bridge pattern are all different but are accessed through a common interface. New implementations can be accommodated by implementing them within this interface.

The Abstract Factory encapsulates the variation of which sets or families of objects can be instantiated. There are many different ways of implementing this pattern. It is useful to note that even if one implementation is initially chosen and then it is determined another way would have been better, the implementation can be changed without affecting any other part of the system (since the interface for the factory does not change, only the way it is implemented). Thus, the notion of the Abstract Factory itself (implementing to an interface) hides all of the variations of how to create the objects.

The Adapter pattern is a tool to be used to take disparate objects and give them a common interface. This is often needed now that I am designing to interfaces as called for in many patterns.

The Facade typically does not encapsulate variation. However, I have seen many cases where a Facade was used to work with a particular subsystem. Then, when another subsystem came along, a Facade for the new subsystem was built with the same interface. This new class was a combination Facade and Adapter in that the primary motivation was simplification, but now had the added constraint of being the same as the one used before so none of the client objects would need to change. Using a Facade this way hides variations in the subsystems being used.

Patterns are not just about encapsulating variation, however. They also identify relationships between variations. I will show more about this in the next section of this book. Referring to the Bridge pattern again, note that the pattern not only defines and encapsulates the variations in the abstraction and implementation, but also defines the relationship between the two sets of variations.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.19.17