模板方法(Template Method)
模板方法模式——在一个方法中定义了一个算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以在不改变算法结构的情况下,重新定义算法中的某些步骤。
原则
好莱坞原则:别调用(打电话给)我们,我们会调用(打电话给)你。
(封装算法块)
类图
Code
origin
public class Coffee {
void prepareRecipe() {
boilWater();
brewCoffeeGrinds();
pourInCup();
addSugerAndMilk();
}
private void boilWater() {
System.
out.println(
"Boiling water");
}
private void brewCoffeeGrinds() {
System.
out.println(
"Dripping coffee through filter");
}
private void pourInCup() {
System.
out.println(
"Pouring into cup");
}
private void addSugerAndMilk() {
System.
out.println(
"Adding Sugar and Milk");
}
}
public class Tea {
void prepareRecipe() {
boilWater();
steepTeaBag();
pourInCup();
addLemon();
}
private void boilWater() {
System.
out.println(
"Boiling water");
}
private void steepTeaBag() {
System.
out.println(
"Steeping the tea");
}
private void pourInCup() {
System.
out.println(
"Pouring into cup");
}
private void addLemon() {
System.
out.println(
"Adding Lemon");
}
}
改进
public abstract class CaffeineBeverage {
final void prepareRecipe() {
boilWater();
brew();
pourInCup();
addCondiments();
}
abstract void addCondiments();
abstract void brew();
public void boilWater() {
System.out.println(
"Boiling water");
}
public void pourInCup() {
System.out.println(
"Pouring into cup");
}
}
public class Coffee extends CaffeineBeverage {
@Override
void brew() {
System.out.println(
"Dripping coffee through filter");
}
@Override
void addCondiments() {
System.out.println(
"Adding Sugar and Milk");
}
}
public class Tea extends CaffeineBeverage {
@Override
void brew() {
System.out.println(
"Steeping the tea");
}
@Override
void addCondiments() {
System.out.println(
"Adding Lemon");
}
}
模板方法
public abstract class AbstractClass {
final
void templateMethod() {
primitiveOperation1();
primitiveOperation2();
concreteOperation();
}
abstract void primitiveOperation1();
abstract void primitiveOperation2();
void concreteOperation() {
}
}
钩子
public abstract class AbstractClass {
final void templateMethod() {
primitiveOperation1();
primitiveOperation2();
concreteOperation();
hook();
}
abstract void primitiveOperation1();
abstract void primitiveOperation2();
final void concreteOperation() {
}
void hook() {}
}
Reference
http://cashow.github.io/head-first-design-patterns-notes-template-method-pattern.html
转载请注明原文地址: https://ju.6miu.com/read-1395.html