Design Patterns Java™ Workbook

(Michael S) #1
Chapter 21. Template Method

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 TEMPLATE METHOD 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 TEMPLATE METHOD when you refactor an algorithm that
appears in multiple methods.


Refactoring to Template Method.............................................................................................................


When you apply TEMPLATE METHOD, classes in a hierarchy share the outline of an algorithm
that you or someone else codes in an abstract superclass. The opportunity for TEMPLATE
METHOD 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 FACTORY METHOD that returns an appropriate subclass
of MachinePlanner.

Free download pdf