模板方法(Template Method)模式定義:java
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 .算法
定義一個操做中的一個算法框架,把一些步驟推遲到子類去實現。模板方法模式讓子類不須要改變算法結構而從新定義特定的算法步驟。app
也就是說:模板方法模式定義了一系列算法步驟,子類能夠去實現或覆蓋其中某些步驟,但不能改變這些步驟的執行順序。框架
下面的代碼是模板方法模式的示例代碼,類HappyPeople的方法celebrateSpringFestival()是一個模板方法,有3個步驟,其中方法travel()是抽象部分,用於子類實現不一樣客戶化邏輯。ide
package pattern.part1.chapter2.template; /** * Date: 2009-11-18 * Time: 0:42:25 */ public class HappyPeopleTestDrive { public static void main(String[] args) { HappyPeople passengerByAir = new PassengerByAir(); HappyPeople passengerByCoach = new PassengerByCoach(); HappyPeople passengerByTrain = new PassengerByTrain(); System.out.println("Let's Go Home For A Grand Family Reunion...\n"); System.out.println("Tom is going home:"); passengerByAir.celebrateSpringFestival(); System.out.println("\nRoss is going home:"); passengerByCoach.celebrateSpringFestival(); System.out.println("\nCatherine is going home:"); passengerByTrain.celebrateSpringFestival(); } }
package pattern.part1.chapter2.template; public abstract class HappyPeople { public void celebrateSpringFestival() { subscribeTicket(); travel(); celebrate(); } protected final void subscribeTicket() { //Buying ticket... System.out.println("Buying ticket..."); } protected abstract void travel(); protected final void celebrate() { //Celebrating Chinese New Year... System.out.println("Happy Chinese New Year!"); } }
package pattern.part1.chapter2.template; /** * Date: 2009-11-18 * Time: 0:23:43 */ public class PassengerByAir extends HappyPeople { @Override protected void travel() { //Traveling by Air... System.out.println("Travelling by Air..."); } }
package pattern.part1.chapter2.template; /** * Date: 2009-11-18 * Time: 0:22:16 */ public class PassengerByCoach extends HappyPeople { @Override protected void travel() { //Travel by Coach... System.out.println("Travelling by Coach..."); } }
package pattern.part1.chapter2.template; /** * Date: 2009-11-18 * Time: 0:20:05 */ public class PassengerByTrain extends HappyPeople { @Override protected void travel() { //Travel by Train... System.out.println("Travelling by Train..."); } }
模版方法模式能夠解決某些場景中的代碼冗餘問題,但也可能引入類的泛濫問題。使用回調能夠避免類的泛濫。指針
回調錶示一段可執行邏輯的引用(或者指針),咱們把該引用(或者指針)傳遞到另一段邏輯(方法)裏供這段邏輯適時調用。code