Design Patterns Java™ Workbook

(Michael S) #1
Chapter 21. Template Method

Figure 21.4. A Machine object can create an appropriate MachinePlanner instance for
itself.

Suppose that you notice that subclasses of Machine include similar techniques for lazy-
initializing a planner. The ShellAssembler class has a ShellPlanner attribute that it
calls planner and that ShellAssembler initializes in its getPlanner() method:


public MachinePlanner getPlanner()
{
if (planner == null)
{
planner = new ShellPlanner(this);
}
return planner;
}


The StarPress class also has a planner attribute but declares it to be of type
StarPressPlanner. The getPlanner() method of StarPress also lazy-initializes the
planner attribute:


public MachinePlanner getPlanner()
{
if (planner == null)
{
planner = new StarPressPlanner(this);
}
return planner;
}


The other subclasses of Machine have similar approaches to creating a planner only when it
is first needed.

Free download pdf