Template Method Pattern: Starbuzz Problem
Template Method Pattern: Starbuzz Problem
TEMPLATE METHOD
PATTERN
By Võ Văn Hải
Email: [email protected]
Blog: http://vovanhai.wordpress.com
Saigon, 01/2010
StarBuzz problem
• Coffee Recipe
– Boil some water
– Brew coffee in boiling water
– Pour coffee in cup
– Add sugar and milk
• Tea Recipe
– Boil some water
– Steep tea in boiling water
– Pour tea in cup
– Add lemon
• Suppose you are required to implement a system
to maintain this
Simple Solution
1
30/01/2010
Simple Solution
2
30/01/2010
prepareRecipe(){
boilWatere();
brew();
pourInCup();
addCondiments();
}
3
30/01/2010
Template Pattern
Encapsulates an algorithm by creating a
template for it.
Defines the skeleton of an algorithm as a set
of steps.
Some methods of the algorithm have to be
implemented by the subclasses – these are
abstract methods in the super class.
The subclasses can redefine certain steps of
the algorithm without changing the algorithm’s
structure.
Some steps of the algorithm are concrete
methods defined in the super class.
4
30/01/2010
Why Hooks
The number of abstract methods used must
be minimized.
Enables a subclass to implement an optional
part of an algorithm.
Enables a subclass to react to a step in the
template method.
Enables the subclass to make a decision for
the abstract class.
5
30/01/2010
Example
Hollywood Principle
The template pattern follows the
hollywood principle.
Principle: Don’t call us, we will call you.
Low-level components are activated by
high-level components.
A low-level component never calls a high-
level component.
In the template pattern the abstract class is
the high-level component and the concrete
classes the low-level components.
6
30/01/2010
Summary
Design Principle: Don’t call us we’ll call you.
Template pattern defines steps of an
algorithm.
Subclasses cannot change the algorithm -
final
Facilitates code reuse.
Similar to the strategy pattern.
The factory pattern is a specialization of
the template pattern.