414 | Chapter 11: Strategy Pattern
Simply by adding setters to the context class, the application has been given a
dynamic way to change which strategy the concrete context class delegates.
Tricks and Skits Reorganization: Clown Planning
Before going on to the next example, we need to consider how the strategy sub-
classes were organized for the task at hand. Keep in mind that no matter how sophis-
ticated or cool your application is, good planning will make it better.
The more components in your system, the moregranularityyour application is said
to have. Granularity affords more flexibility, and that’s a good thing. However,
greater granularity also leads to a greater number of classes, often adding housekeep-
ing headaches.
To optimize your application, especially one using the Strategy design pattern where
you can have a large number of both concrete contexts and strategies, you need to
plan. Taking a closer look at the clown example, we can see where our planning was
incomplete.
Starting with the trick strategies, the structure allows for only a single trick per
clown. So, we might want to reorganize the strategies from what we have to some-
thing like that shown in Table 11-1.
Now, instead of a single trick interface, it has three. Additionally, a general algo-
rithm covering any tricks in the category is covered as well (any object, any shapes
and any magic). To cover contingencies, the context class retains its ability to
dynamically add a strategy to an instance of a concrete context object. The skit strat-
egies can be reorganized as well, and new strategies can be added as the application
grows and changes.
Working with String Strategies
The best aspect of the Strategy design pattern is its ability to allow change and adap-
tation. The design pattern is a virtual poster child for composition, where change
and flexibility are handled with aplomb. Also, it’s a great tool for working with algo-
rithms large and small.
Table 11-1. Strategies
Juggle Tricks Balloon Tricks Magic Tricks
Balls Animal shapes Card tricks
Rings Human shapes Escape tricks
Flaming Torches Politicians Disappearing children
Any objects Any shapes Any magic