什麼是模板方法模式
定義:
定義了統一的算法框架,將部分實現延遲到子類中實現。 使得子類在不改變算法結構的同時可以重新定義該算法框架的某些定義步驟。
如何實現模板方法模式
業務和場景分析
uml
RefreshBeverage.java
package com.imooc.pattern.template;
/*
* 抽象基類,爲所有子類提供一個算法框架
*
* 提神飲料
*/
public abstract class RefreshBeverage {
/*
* 製備飲料的模板方法
* 封裝了所有子類共同遵循的算法框架
*/
public final void prepareBeverageTemplate(){
//步驟1 將水煮沸
boilWater();
//步驟2 泡製飲料
brew();
//步驟3 將飲料倒入杯中
pourInCup();
if(isCustomerWantsCondiments()){
//步驟4 加入調味料
addCondiments();
}
}
/*
* Hook, 鉤子函數,提供一個默認或空的實現
* 具體的子類可以自行決定是否掛鉤以及如何掛鉤
* 詢問用戶是否加入調料
*/
protected boolean isCustomerWantsCondiments() {
return true;
}
/*
* 基本方法,將水煮沸
*/
private void boilWater() {
System.out.println("將水煮沸");
}
/*
* 基本方法,將飲料倒入杯中
*/
private void pourInCup() {
System.out.println("將飲料倒入杯中");
}
/*
* 抽象的基本方法,泡製飲料
*/
protected abstract void brew();
/*
* 抽象的基本方法, 加入調味料
*/
protected abstract void addCondiments();
}
Coffee.java
package com.imooc.pattern.template;
/*
* 具體子類,提供了咖啡製備的具體實現
*/
public class Coffee extends RefreshBeverage {
@Override
protected void brew() {
System.out.println("用沸水沖泡咖啡");
}
@Override
protected void addCondiments() {
System.out.println("加入糖和牛奶");
}
}
Tea.java
package com.imooc.pattern.template;
/*
* 具體子類,提供了製備茶的具體實現
*/
public class Tea extends RefreshBeverage {
@Override
protected void brew() {
System.out.println("用80度的熱水浸泡茶葉5分鐘");
}
@Override
protected void addCondiments() {
System.out.println("加入檸檬");
}
@Override
/*
* 子類通過覆蓋的形式選擇掛載鉤子函數
* @see com.imooc.pattern.template.RefreshBeverage#isCustomerWantsCondiments()
*/
protected boolean isCustomerWantsCondiments(){
return false;
}
}
RefreshBeverageTest.java
package com.imooc.pattern.template;
public class RefreshBeverageTest {
public static void main(String[] args) {
System.out.println("製備咖啡...");
RefreshBeverage b1 = new Coffee();
b1.prepareBeverageTemplate();
System.out.println("咖啡好了!");
System.out.println("\n******************************************");
System.out.println("製備茶...");
RefreshBeverage b2 = new Tea();
b2.prepareBeverageTemplate();
System.out.println("茶好了!");
}
}
模板方法模式的特點
(https://en.wikipedia.org/wiki/Template_method_pattern) The template method is used in frameworks, where each implements the invariant parts of a domain’s architecture, leaving “placeholders” for customisation options. This is an example of inversion of control. Reasons to use the template method are to