334 | Chapter 9: Template Method Pattern
method. The child classes just give the details to the operations within an algorithm
controlled by the parent class.
The template method itself is locked using thefinalattribute. By addingfinalto a
function, the function cannot be overridden. At first, this may seem to contradict
everything being said about leaving some of the details to the subclasses by overrid-
ing the operations. However, you don’t lock the abstract functions (operations), only
the template method. Figure 9-1 illustrates this arrangement.
As you can see in Figure 9-2, the operations that make up the template method are
not locked. So the subclasses can override the operations all they need. However,
subclasses cannot change the order of the operations that make up the algorithm in
the template method itself.
Finally, you can add an optionalhookoperation. On one level, a hook is nothing
more than a method that can be overridden in the context of a Template Method
design. It also can be seen as a back door where an implementation (subclass) can
hook into an algorithm. Because the hook concept is best understood in the context
of an example, further discussion will be deferred to later on in the chapter.
The Template Method Model
Upon first encountering the Template Method, most developers are struck by the
simplicity of the pattern’s design, and then by its utility and clarity. Even though the
design as depicted in the class diagram in Figure 9-2 is very simple, it can be used to
solve a wide range of problems.
Figure 9-1. Locked Template Method
class AbstractClass
{
final function templateMethod()
{
operationA()
operationB()
operationC()
}
function operationA()
{}
function operationB()
{}
function operationC()
{}
}
Locked up
Unlocked