设计模式11-模板方法模式
package DesignPattern;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TemplateMethodPattern {
//模板方法模式
//要点在于共享算法流程,这类似于工厂方法模式
//不同之处在于:
// 工厂方法模式关注产品的最初的复杂创建,并提供给子类自定以创建的接口
// 模板方法模式关注产品加工流程的方法,提供给子类自定义创建接口
public static abstract class CaffeineBeverageWithHook{
final 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");
}
//Hook
boolean customerWantsCondiments(){
return true;
}
}
public static class CoffeeWithHook extends CaffeineBeverageWithHook{
@Override
public void brew(){
System.out.println("Drpping Coffee through filter");
}
@Override
void addCondiments() {
System.out.println("Adding Sugar and milk");
}
@Override
boolean customerWantsCondiments() {
String answer = getUserInput();
if (answer.startsWith("y"))
return true;
return false;
}
private String getUserInput(){
String answer=null;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("would you want condiments?");
try {
answer=in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if(answer==null)answer="no";
return answer;
}
}
public static void main(String[] args) {
CoffeeWithHook cwh = new CoffeeWithHook();
cwh.prepareRecipe();
}
}
I'm a fucKing fake coder!