Template Method (模板方法模式)

要想实现 模板方法模式,涉及到两个角色:1.抽象模板角色---父类(抽象的) 2.具体模板角色---子类

就是父类和子类继承的表现

抽象模板角色这个类里 定义了几个抽象方法,供子类去实现具体操作,还定义了一个模板方法(template),以告诉子类去实现这些方法要有一定的顺序去执行, 这种设计模式在JUnit中的setUp(),runTest(),tearDown()体现了,

源码:

public void runBare() throws Throwable {  setUp();
 try {   runTest();    //而这里面又涉及到 适配器模式  }
 finally {   tearDown();  } }

Template Method  UML图:

代码演示:

AbstractClass.java

[java] view plain copy
  1. package com.template ;  
  2.   
  3. public abstract class AbstractClass  
  4. {  
  5.     //如果把类AbstractClass定义成接口,实现不了以下操作  
  6.     public void template()  
  7.     {  
  8.         this.operation1() ;  
  9.         this.operation2() ;  
  10.         this.operation3() ;  
  11.         
  12.     }  
  13.     public abstract void operation1() ;  
  14.     public abstract void operation2() ;  
  15.     public abstract void operation3() ;  
  16.       
  17.   
  18. }  

ConcreteClass.java

[java] view plain copy
  1. package com.template ;  
  2.   
  3. public class ConcreteClass extends AbstractClass  
  4. {  
  5.     public void operation1()  
  6.     {  
  7.         System.out.println("operation-1") ;  
  8.     }  
  9.   
  10.     public void operation2()  
  11.     {  
  12.         System.out.println("operation-2") ;  
  13.     }  
  14.   
  15.     public void operation3()  
  16.     {  
  17.         System.out.println("operation-3") ;  
  18.     }  
  19.   
  20.       
  21. }  

Client.java

[java] view plain copy
  1. package com.template ;  
  2.   
  3. class Client   
  4. {  
  5.     public static void main(String[] args)   
  6.     {  
  7.         AbstractClass ac = new ConcreteClass() ;  
  8.         ac.template() ;  
  9.     }  
  10. }  
原文地址:https://www.cnblogs.com/hoobey/p/5294396.html