Template Method
模板方法定义了一个算法的步骤,并允许子类为一个或多个步骤提供实现.
它是一个骨架,在框架的设计中多用此设计模式.
对模板方法进行挂钩:
钩子是一种被声明在抽象类中的方法,但只有空的或者默认的实现.钩子的存在,
可以让子灰有能力对算法的不同点进行挂钩.要不要挂钩,由子类自行决定.
好莱坞原则:
高层组件对低层组件的方式是"别调用我们,我们会调用你".
public abstract class CaffeineBeverage {
//不希望子类覆盖此方法,声明为final
final void prepareRecipe() {
boilWater();
brew();
pourInCup();
addCondiments();
}
abstract void brew();
abstract void addCondiments();
void boilWater() {
System.out.println("Boiling water");
}
void pourInCup() {
System.out.println("Pouring into cup");
}
}
public class Tea extends CaffeineBeverage {
public void brew() {
System.out.println("Steeping the tea");
}
public void addCondiments() {
System.out.println("Adding Lemon");
}
}
public class Coffee extends CaffeineBeverage {
public void brew() {
System.out.println("Dripping Coffee through filter");
}
public void addCondiments() {
System.out.println("Adding Sugar and Milk");
}
}
对模板方法使用钩子:
public abstract class CaffeineBeverageWithHook {
void prepareRecipe() {
boilWater();
brew();
pourInCup();
if (customerWantsCondiments()) {
addCondiments();
}
}
abstract void brew();
abstract void addCondiments();
void boilWater() {
System.out.println("Boiling water");
}
void pourInCup() {
System.out.println("Pouring into cup");
}
boolean customerWantsCondiments() {
return true;
}
}
import java.io.*;
public class CoffeeWithHook extends CaffeineBeverageWithHook {
public void brew() {
System.out.println("Dripping Coffee through filter");
}
public void addCondiments() {
System.out.println("Adding Sugar and Milk");
}
public boolean customerWantsCondiments() {
String answer = getUserInput();
if (answer.toLowerCase().startsWith("y")) {
return true;
} else {
return false;
}
}
private String getUserInput() {
String answer = null;
System.out.print("Would you like milk and sugar with your coffee (y/n)? ");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
answer = in.readLine();
} catch (IOException ioe) {
System.err.println("IO error trying to read your answer");
}
if (answer == null) {
return "no";
}
return answer;
}
}
分享到:
相关推荐
java的23种常用设计模式:模板方法模式
适合20分钟左右讲解的模板方法模式。 自己上课用的。
模板方法模式:定义一个操作中的算法骨架,而将一些步骤延迟到子类中,模板方法使得子类可以不改变一个算法的结构即可重新定义该算法的某些特定步骤。
设计模式-模板方法模式(讲解及其实现代码)
设计模式C++学习之模板方法模式(Template Method)
设计模式模板方法模式PPT学习教案.pptx
模板方法模式的示例代码和文档,学习模板方法模式的参考资料。
模板方法模式是基于继承的代码复用基本技术,模板方法模式的结构和用法也是面向对象设计的核心之一。在模板方法模式中,可以将相同的代码放在父类中,而将不同的方法实现放在不同的子类中。 在模板方法模式中,我们...
策略模式结合模板方法模式
iOS模板方法模式使用心得demo
模板方法模式例子代码
处理层的设计采用了设计模式中的策略模式、模板方法模式和工厂模式。 Server端和Client端的实现也采用了分层的设计方式,包含自定义的模型层、视图层和控制层。 说明:程序采用配置文件的方式进行初始化,运行时时请...
设计模式--模板方法模式java例子
Head First 设计模式 (八) 模板方法模式(Template Method pattern) C++实现
模板方法模式是一种行为设计模式,它在一个方法中定义算法的骨架,将一些步骤延迟到子类中实现。 具体来说,模板方法模式的关键特点包括: 抽象类:在抽象类中定义一个模板方法,该方法给出了算法的框架。 具体...
将《Head First 设计模式》(中文版)按章节进行了分割,每章一个文件,方便大家下载。