Summary | 423
Summary
After examining some applications using the Strategy design pattern, you can see the
scope of possibilities for it as a design pattern. It’s certainly a showcase for good
OOP practices. Perhaps most obvious is how it uses composition instead of inherit-
ance to develop and use the algorithms. However, it still uses the basic OOP feature
ofinheritance in its concrete context classes.
Furthermore, you can clearly seepolymorphismin the variety of ways the different
strategies are implemented. Each of the interfaces demonstratesabstractionalong
with the main context class. All the strategiesencapsulatean algorithm, and each
serves as a delegate to another class. So there you have it, the four basic elements of
good OOP:
- Inheritance
- Polymorphism
- Abstraction
- Encapsulation
As we saw in this chapter in the section on the key OOP practices, the Strategy
design pattern demonstrates several other good OOP practices in addition to the
basics.
So, while we believe that the Strategy design pattern certainly demonstrates funda-
mental OOP practices, it’s still a distinct design pattern. Ironically, this fact is most
obvious when you compare it to the State design pattern—the pattern it’s often
accused of duplicating. The State pattern encapsulates states and state contexts, and
the Strategy pattern encapsulates algorithms. Both have different intents but these
intentions are masked by the almost identical class diagrams. Only when you under-
stand and use each one do the differences manifest themselves. As these differences
become clear, you can see the actual use of the State and Strategy patterns as solu-
tions to different kinds of problems. Since the definition of design patterns is that of
design solution to recurring problems, we can see that the Strategy design pattern
clearly meets this fundamental criterion.
Figure 11-5. Output from TestStringStrategy