模板设计模式–基于抽象类的设计模式:
- 模板设计模式的格式是:抽象父类(含钩子方法)+子类覆写
模板设计模式从字面上理解就是给系统一个统一的步骤做模板,让所有的工程都统一,他的存在在代码中使算法更加集中,保护了算法不被更改,并且因为使用这个模式的前提是大多数的内容都是重复的,如果分开写就会有大量重复代码,所以使用模板模式会使代码复用最大化,如果核心算法升级了有需要更改,在这种模式下也更容易更改,不需要在大量的工程中逐个更改。
代码:
package com.irilia.TemplateDesignPattern;
import java.util.Scanner;
abstract class CaffeineBeverage{
//特定的步骤不能被随便更改所以用final修饰
final void prepareRecipe(){
boilWater();
brew();
pourInCup();
//子类决定要不要添加调料
if(CustomerWantsCondiments()){
addCondiments();
}
}
abstract void brew();
abstract void addCondiments();
void boilWater(){
System.out.println("烧开水");
}
void pourInCup(){
System.out.println("倒进杯子");
}
boolean CustomerWantsCondiments(){
return true;
}
}
class Tea extends CaffeineBeverage{
@Override
void brew() {
System.out.println("冲茶叶");
}
@Override
void addCondiments() {
System.out.println("加柠檬");
}
}
class Coffee extends CaffeineBeverage{
@Override
void brew() {
System.out.println("泡咖啡");
}
@Override
void addCondiments() {
System.out.println("加牛奶");
}
//实现钩子方法
public boolean CustomerWantsCondiments(){
String answer = getUserInput();
if(answer.equals("y")){
return true;
}else{
return false;
}
}
private String getUserInput(){
String answer = null;
System.out.println("您想在牛奶中加入糖和牛奶吗(y/n)");
Scanner in = new Scanner(System.in);
answer = in.nextLine();
return answer;
}
}
public class TemplateDesignPatternTest{
public static void main(String[] args) {
CaffeineBeverage tea = new Tea();
CaffeineBeverage coffee = new Coffee();
tea.prepareRecipe();
coffee.prepareRecipe();
}
}