模板方法模式其實就是將類似步驟的類抽取相同的部分到抽象類中,不一樣部分在抽象類中定義爲抽象方法,讓具體類去實現。java
以泡茶和泡咖啡做爲例子。他們都須要煮水,泡茶或咖啡,過濾,加檸檬或糖ide
1.抽象出來的類blog
//把相同的煮水和過濾抽出來,至於泡的是茶仍是咖啡,加的是檸檬仍是糖則泛化爲抽象 public abstract class CaffeineBeverage { final void prepareRecipe(){ boilWater(); brew(); pourInCup(); addCondiments(); } abstract void addCondiments(); void pourInCup() { // TODO Auto-generated method stub System.out.println("Pouring in cup"); } abstract void brew(); private void boilWater() { // TODO Auto-generated method stub System.out.println("Boiling water"); } }
2.具體實現的類ip
public class Coffee extends CaffeineBeverage { @Override void addCondiments() { // TODO Auto-generated method stub System.out.println("Adding sugar and milk"); } @Override void brew() { // TODO Auto-generated method stub System.out.println("dripping coffee through filter"); } } public class Tea extends CaffeineBeverage{ @Override void addCondiments() { // TODO Auto-generated method stub System.out.println("Adding Lemon"); } @Override void brew() { // TODO Auto-generated method stub System.out.println("Steeping the tea"); } }