模板方法模式
定义
只定义算法框架,而将一些步骤的实现延迟到子类。
通过模板方法,子类可以重新定义算法的某些步骤,而不用改变算法的结构。
类图
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gl1rhSCA-1596243318723)(https://camo.githubusercontent.com/b71fede146c0f8d211d29799abb9f94259c0ad7c/68747470733a2f2f63732d6e6f7465732d313235363130393739362e636f732e61702d6775616e677a686f752e6d7971636c6f75642e636f6d2f61633661373934622d363863302d343836632d393032662d3864393838656565353736362e706e67)]
实现
冲咖啡和冲茶都有类似的流程,但是某些步骤会有点不一样,要求复用那些相同步骤的代码。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2PJhD4v3-1596243318726)(https://camo.githubusercontent.com/12fe3db96bd447effced5c6205814b6f6c7fe1ba/68747470733a2f2f63732d6e6f7465732d313235363130393739362e636f732e61702d6775616e677a686f752e6d7971636c6f75642e636f6d2f31313233363439382d313431372d343663652d613162302d6531303035343235363935352e706e67)]
public abstract class CaffeineBeverage {
final void prepareRecipe() {
boilWater();
brew();
pourInCup();
addCondiments();
}
abstract void brew();
abstract void addCondiments();
void boilWater() {
System.out.println("boilWater");
}
void pourInCup() {
System.out.println("pourInCup");
}
}
public class Coffee extends CaffeineBeverage {
@Override
void brew() {
System.out.println("Coffee.brew");
}
@Override
void addCondiments() {
System.out.println("Coffee.addCondiments");
}
}
public class Tea extends CaffeineBeverage {
@Override
void brew() {
System.out.println("Tea.brew");
}
@Override
void addCondiments() {
System.out.println("Tea.addCondiments");
}
}
public class Client {
public static void main(String[] args) {
CaffeineBeverage caffeineBeverage = new Coffee();
caffeineBeverage.prepareRecipe();
System.out.println("-----------");
caffeineBeverage = new Tea();
caffeineBeverage.prepareRecipe();
}
}