模板方法模式(Template Method Pattern)

模板方法(Template Method)模式定义:

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 .

定义一个操作中的一个算法框架,把一些步骤推迟到子类去实现。模板方法模式让子类不需要改变算法结构而重新定义特定的算法步骤。

也就是说:模板方法模式定义了一系列算法步骤,子类可以去实现或覆盖其中某些步骤,但不能改变这些步骤的执行顺序。

下面的代码是模板方法模式的示例代码,类HappyPeople的方法celebrateSpringFestival()是一个模板方法,有3个步骤,其中方法travel()是抽象部分,用于子类实现不同客户化逻辑。

01 package pattern.part1.chapter2.template;
02  
03 /**
04  * Date: 2009-11-18
05  * Time: 0:42:25
06  */
07 public class HappyPeopleTestDrive {
08     public static void main(String[] args) {
09         HappyPeople passengerByAir = new PassengerByAir();
10         HappyPeople passengerByCoach = new PassengerByCoach();
11         HappyPeople passengerByTrain = new PassengerByTrain();
12  
13         System.out.println("Let's Go Home For A Grand Family Reunion...\n");
14  
15         System.out.println("Tom is going home:");
16         passengerByAir.celebrateSpringFestival();
17  
18         System.out.println("\nRoss is going home:");
19         passengerByCoach.celebrateSpringFestival();
20  
21         System.out.println("\nCatherine is going home:");
22         passengerByTrain.celebrateSpringFestival();
23     }
24 }

01 package pattern.part1.chapter2.template;
02  
03  
04 public abstract class HappyPeople {
05     public void celebrateSpringFestival() {
06         subscribeTicket();
07         travel();
08         celebrate();
09     }
10  
11     protected final void subscribeTicket() {
12         //Buying ticket...
13         System.out.println("Buying ticket...");
14     }
15  
16     protected abstract void travel();
17  
18     protected final void celebrate() {
19         //Celebrating Chinese New Year...
20         System.out.println("Happy Chinese New Year!");
21     }
22 }

01 package pattern.part1.chapter2.template;
02  
03 /**
04  * Date: 2009-11-18
05  * Time: 0:23:43
06  */
07 public class PassengerByAir extends HappyPeople {
08     @Override
09     protected void travel() {
10         //Traveling by Air...
11         System.out.println("Travelling by Air...");
12     }
13 }

01 package pattern.part1.chapter2.template;
02  
03 /**
04  * Date: 2009-11-18
05  * Time: 0:22:16
06  */
07 public class PassengerByCoach extends HappyPeople {
08     @Override
09     protected void travel() {
10         //Travel by Coach...
11         System.out.println("Travelling by Coach...");
12     }
13 }

01 package pattern.part1.chapter2.template;
02  
03 /**
04  * Date: 2009-11-18
05  * Time: 0:20:05
06  */
07 public class PassengerByTrain extends HappyPeople {
08     @Override
09     protected void travel() {
10         //Travel by Train...
11         System.out.println("Travelling by Train...");
12     }
13 }

模版方法模式可以解决某些场景中的代码冗余问题,但也可能引入类的泛滥问题。使用回调可以避免类的泛滥。

回调表示一段可执行逻辑的引用(或者指针),我们把该引用(或者指针)传递到另外一段逻辑(方法)里供这段逻辑适时调用。

你可能感兴趣的:(模板方法模式(Template Method Pattern))