Intro
Many of us are living on caffein beverages. Some of us drink coffee, some of us drink tea. Check out the steps needed to make a coffee:
- Boil some water
- Brew Coffee in boiling water
- Pour coffee in cup
- Add sugar and milk
and steps to make a tea:
- Boil some water
- Brew tea in boiling water
- Pour tea in cup
- Add lemon
We can already see there exists an underlying similar algorithm for the two processes, namely:
- Boil water
- Brew
- Pour in cup
- Add condiments
Of course, we may add different condiments to tea and coffee. That should be left for the subclass to implement.
So yes, this is it! Abstract the steps into a template method (encapsulating algorithms), then leaving specific step(s) in the algorithm to the subclasses. This is the intuition for our Template Method Pattern
Definition
The Template Method Pattern defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method let's subclasses redefine certain steps of an algorithm without changing the algorithm's structure.
When we implement this, we usually declare the template method as final
, and to-be-implemented methods as abstract
. We also define one or many hook
method, which are optional for the subclasses to implement.
Design Principle
The Hollywood Principle
Don't call us, we'll call you.
This principle states that one should avoid the circular dependencies between up and low level components. -> Just let the high-level component controls the low-level components, but not the converse.
Examples
Template Method pattern is particularly useful in frameworks.
Java Arrays Sorting
Say we have an array of self-defined classes Duck
, to use Sorting provided by Java, we need to make Duck
implement Comparable
interface and implement compareTo
method.
Swing JFrame
JFrame's update algorithm calls paint()
, But by default paint()
does nothing. It is a hook and can(should) be overwritten.
Top comments (0)