Abstract Server


You might be thinking that you could inherit a Switch subclass that would control something other than a light, as in Figure 33-2. But this doesn't solve the problem, because FanSwitch still inherits the dependency on Light. Wherever you take a FanSwitch, you'll have to bring Light along. In any case, that particular inheritance relationship also violates DIP.

Figure 33-2. A bad way to extend Switch


To solve the problem, we invoke one of the simplest of all design patterns: ABSTRACT SERVER (see Figure 33-3). By introducing an interface between the Switch and the Light, we have made it possible for Switch to control anything that implements that interface. This immediately satisfies both DIP and OCP.

Figure 33-3. ABSTRACT SERVER solution to the table lamp problem


As an interesting aside, note that the interface is named for its client. It is called Switchable rather than Light. We've talked about this before, and we'll probably do so again. Interfaces belong to the client, not to the derivative. The logical binding between the client and the interface is stronger than that between the interface and its derivatives. The logical binding is so strong that it makes no sense to deploy Switch without Switchable, and yet it makes perfect sense to deploy Switchable without Light. The strength of the logical bonds is at odds with the strength of the physical bonds. Inheritance is a much stronger physical bond than association is.

In the early 1990s, we used to think that the physical bond ruled. Reputable books recommended that inheritance hierarchies be placed together in the same physical package. This seemed to make sense, since inheritance is such a strong physical bond. But over the past decade, we have learned that the physical strength of inheritance is misleading and that inheritance hierarchies should usually not be packaged together. Rather, clients tend to be packaged with the interfaces they control.

This misalignment of the strength of logical and physical bonds is an artifact of statically typed languages, such as C#. Dynamically typed languages, such as Smalltalk, Python, and Ruby, don't have the misalignment, because they don't use inheritance to achieve polymorphic behavior.




Agile Principles, Patterns, and Practices in C#
Agile Principles, Patterns, and Practices in C#
ISBN: 0131857258
EAN: 2147483647
Year: 2006
Pages: 272

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net