Java Reference
In-Depth Information
public Firework recommend(Customer c)
{
return (Firework) LikeMyStuff.suggest(c);
}
}
This code creates a singleton object that uses the LikeMyStuff engine and that clients
can use as an instance of the Advisor interface.
SOLUTION 23.4
Your code should look something like:
public Firework getRecommended()
{
return getAdvisor().recommend(this);
}
The getAdvisor() method still has a complex if statement, but once the advisor is
known, polymorphism does all the work.
SOLUTION 23.5
The presence of multiple, similar singletons is reminiscent of the FLY-WEIGHT pattern, which
organizes a group of similar, shareable, immutable objects. To this point, Design Patterns
(Gamma et al. 1995) mentions that "S TRATEGY objects often make good flyweights" (p. 323).
On the other hand, the intent of F LYWEIGHT is to use sharing to support large numbers of
fine-grained objects efficiently. It's a bit of a stretch to imagine that you'll ever have "large
numbers" of alternative strategies.
SOLUTION 23.6
Is a reusable sort routine an example of T EMPLATE M ETHOD or an example of S TRATEGY ?
For S TRATEGY : According to Design Patterns, T EMPLATE M ETHOD lets "subclasses"
redefine certain steps of an algorithm. But the Collections.sort() method
doesn't work with subclasses; it requires a Comparator instance. Each instance of
Comparator provides a new method and thus a new algorithm and a new strategy.
The sort() method is a good example of S TRATEGY .
For T EMPLATE M ETHOD : There are many sorting algorithms, but
Collections.sort() uses only one, a merge sort. Changing the algorithm would
mean changing to, say, a heap sort or a bubble sort. The intent of S TRATEGY is to let
you plug in different algorithms. That doesn't happen here. The intent of T EMPLATE
M ETHOD is to let you plug a step into an algorithm. That is precisely how the sort()
method works.
Search WWH ::




Custom Search