Java Reference
In-Depth Information
difference leads to different problems in modeling states and strategies. For example,
transitions are important when modeling states but usually irrelevant when choosing
a strategy. Another difference is that S TRATEGY might allow a client to select or to provide
a strategy, an idea that rarely applies to S TATE . On the other hand, the differences in modeling
states and strategies may seem subtle. Certainly, the reliance on polymorphism makes S TATE
and S TRATEGY appear almost identical structurally. Either way, if you decide that these are or
are not two separate patterns, you will be in good company.
Comparing Strategy and Template Method
Chapter 21, Template Method, described sorting as an example of the T EMPLATE M ETHOD
pattern. You can use the sort() algorithm from the Collections class to sort any list of
objects, so long as you supply a step to compare two objects. But you might argue that when
you supply a comparison step to a sorting algorithm, you are changing the strategy. For
instance, if you are selling rockets, presenting them sorted by price is a different marketing
strategy from presenting them sorted by thrust.
CHALLENGE 23.6
Provide an argument as to whether the Collections.sort() method provides
an example of T EMPLATE M ETHOD or an example of S TRATEGY .
Summary
Strategies that occur in the real world may not naturally lie down as separate methods in a
collection of classes. Logic that models alternative strategies may appear in a single class,
often in a single method. Such methods may be too complicated and may mix strategy-
selection logic with strategy execution.
To simplify such code, create a group of classes, one for each strategy. Define an operation
and distribute it across these classes. This lets each class encapsulate one strategy, creating
simpler code. You also need to arrange for the client that uses a strategy to be able to select
one. This selection code may be complex even after refactoring, but you should be able to
reduce this code so that it is nearly equivalent to pseudocode that describes strategy selection
in the problem domain.
Typically, a client will hold a selected strategy in a context variable. This makes the execution
of a strategy a simple matter of forwarding the strategic operation call to the context, using
polymorphism to execute the right strategy. By encapsulating alternative strategies in separate
classes that each implement a common operation, the S TRATEGY pattern lets you create clean,
simple code that models a family of approaches to solving a problem.
Search WWH ::




Custom Search