400 | Chapter 11: Strategy Pattern
say that the Context class (aggregator)ownsthe Strategy interface (aggregate), just as
in the State design pattern. (See Figure 10-3 in Chapter 10.) As you will see in the
examples, the Context class aggregates the Strategy operations. Because aggregation
is so fundamental to many of the design patterns and an integral part of OOP, look
for its actual use in the examples. The Strategy design pattern is one of the best
sources of clear examples showing aggregation at work.
Key OOP Concepts Used with the Strategy Pattern
David Geary (JavaWorld.com, 04/26/02) points out that the Strategy pattern embod-
ies several of the OOP principles put forth by Gamma, Helm, Johnson and Vlissides.
One of those principles is:
Encapsulate the concept that varies
Eric and Elisabeth Freeman (Head First Design Patterns, O’Reilly 2004) make the
same point in discussing the Strategy pattern, and we’re not ones to break tradition
and miss an important connection between a design pattern and an OOP concept.
Encapsulating Variation
In Chapter 10, you saw that with the State design pattern, the states varied in the
video player, and so the State object encapsulated the state-dependent behavior, such
as playing and stopping the video. With the Strategy pattern, the Strategy object
encapsulates algorithms. What both these design patterns have in common is that
the elements that change are encapsulated. (As a hint of what is encapsulated, look
at the name of the class. In both the State and Strategy classes, the encapsulating
object is the name of the class—check the class diagrams.)
More important is why GoF suggests encapsulating those concepts that vary. Essen-
tially, if you encapsulate those parts that vary, then, when you change the applica-
tion, you’ll have fewer surprises. Encapsulated concepts allow the objects in object-
oriented programming to act like objects. Rather than being sticky-glued to and
dependent on other elements in a single program, encapsulated objects can act in
concert with any new element added to the application, because they can vary inde-
pendent of other objects.
To better see what it means to encapsulate what varies, consider a script from an
example in this chapter with and without encapsulation. This involves clowns and
what they do in clown venues.
Unencapsulated version (pseudocode)
class Clown {
function juggle( ) {
//juggle code
}