Java Reference
In-Depth Information
public void dischargePaste()
{
super.dischargePaste();
getFactory().collectPaste(this);
}
This method uses a Factory singleton to collect discarded paste from a star press. This is
dangerous code, though, because paste collection is a surprising side effect. Developers at
Aster will certainly be unaware that you're defining dischargePaste() in this way. If
they modify their code to discharge paste at a time that you don't want to collect it, an error
will occur.
Developers usually strive to solve problems by writing code. But here the challenge is to
solve a problem by communicating with other developers.
CHALLENGE 21.3
Write a note to the developers at Aster, asking for a change that will let you safely
collect discarded star paste before the machine flushes its processing area.
The step that a subclass supplies in T EMPLATE M ETHOD may be required to complete the
algorithm, or it may be an optional step that hooks in a subclass's code, often at another
developer's request. Although the intent of the pattern is to let a separate class define part of
an algorithm, you can also apply T EMPLATE M ETHOD when you refactor an algorithm that
appears in multiple methods.
Refactoring to Template Method
When you apply T EMPLATE M ETHOD , classes in a hierarchy share the outline of an algorithm
that you or someone else codes in an abstract superclass. The opportunity for T EMPLATE
M ETHOD may also crop up when you implement similar algorithms in more than one method.
Consider the Machine and MachinePlanner parallel hierarchy that you worked with in
Chapter 16, Factory Method. As Figure 21.4 shows, the Machine class provides
a createPlanner() method as a F ACTORY M ETHOD that returns an appropriate subclass
of MachinePlanner .
Search WWH ::




Custom Search