模板模式
2016-05-21 本文已影响19人
keith666
Intent
- Define the skeleton of an algorithm in an operation, deferring some steps to client subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.
- Base class declares algorithm 'placeholders', and derived classes implement the placeholders.
Structure

- 代码:
public class Template {
abstract class Beverage {
// template method, make it final so that it can not be redefined
final void prepareRecipe() {
boilWater();
brew();
pourInCup();
if (wantCondiments())
addCondiments();
}
abstract void brew();
abstract void addCondiments();
void boilWater() {
System.out.println("Boiling water");
}
void pourInCup() {
System.out.println("Pouring into a cup");
}
// hook method, it is up to subclass to decide whether to override it or not
// the hook method make the algorithm structure more flexible
boolean wantCondiments() {
return true;
}
}
class Coffee extends Beverage {
@Override
void brew() {
System.out.println("Dripping Coffee through filter");
}
@Override
void addCondiments() {
System.out.println("Adding Sugar and Milk");
}
}
class Tea extends Beverage {
@Override
void brew() {
System.out.println("Steeping the tea");
}
@Override
void addCondiments() {
System.out.println("Adding Lemon");
}
@Override
boolean wantCondiments() {
return false;
}
}
private void test() {
Coffee coffee = new Coffee();
Tea tea = new Tea();
coffee.prepareRecipe();
tea.prepareRecipe();
}
public static void main(String[] args) {
Template template = new Template();
template.test();
}
}
- Output
Boiling water
Dripping Coffee through filter
Pouring into a cup
Adding Sugar and Milk
Boiling water
Steeping the tea
Pouring into a cup