1.模版方法的定義
模版方法的英文定義為:
Template Method Pattern: Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.
翻譯過來的意思是:
模板方法模式:定義一個操作中算法的框架,而將一些步驟延遲到子類中。模板方法模式使得子類可以不改變一個算法的結構即可重定義該算法的某些特定步驟。
這種模式在我們開發中經常會用到,一個簡單的例子,我們在抽象類中定義若干個基本的操作,在具體的實現類中定義模版方法對基本方法實現聚合。這種實現方式就可以稱為模版方法模式
2.模版方法通用模版
對於程序員來說,一天的工作中有很多個基本的工作項目組成,其中包括:簽到、早會、需求討論、功能開發、鏈調、午飯、bug修復等幾項基本工作內容組成。而對於每一個人每天的工作流程又是不一樣的,針對此功能,可以設計出以下類圖:

基本方法:
其中簽到、早會等基本工作項
模版方法:
模版方法為基本方法的不同組合,從而完成不同的邏輯,可以針對不同的組合定義不同的模版類,也可以在同一個類中實現不同的組合。
代碼如下:
public abstract class WorkAbstractService {
protected void sign(){
//簽到
}
protected void morningMeeting(){
//早會
}
protected void requirementsDiscussion(){
//需求討論
}
protected void develop(){
//功能開發
}
protected void eat(){
//午飯
}
protected void debug(){
//聯調
}
protected void fixBug(){
//修復bug
}
}
public class WorkServiceImpl extends WorkAbstractService{
public void workFlow1(){
//簽到-早會-需求討論-午飯-開發-聯調-修復bug
sign();
morningMeeting();
requirementsDiscussion();
eat();
develop();
debug();
fixBug();
}
public void workFlow2(){
//簽到-需求討論-開發-午飯-聯調-修復bug
sign();
requirementsDiscussion();
develop();
eat();
develop();
fixBug();
}
}
3.模版方法的優缺點
優點:
1.封裝不變部分,擴展可變部分
2.提取公共功能部分,便於維護
4.模版方法的使用場景
1.多個子類有公共的方法,並且邏輯基本相同
2.重構的時候,模版方法是一個經常使用的模式,把相同的代碼提取到父類中,然后通過鈎子函數約束其行為。
