1. 概念:定义一个算法的骨架,而将一些实现步骤延迟到子类中。

    把不变的行为搬到超类,去除子类中重复的代码来体现他的优势。

2. UML图:

Java之模板方法模式(Template Method)
    





            
Java之模板方法模式(Template Method)

3.代码:

public abstract class Templete
  private void beforeOperation()
  
    System.out.println("This acton before the operation!"); 
  
    
  private void afterOperation()
  
    System.out.println("This acton after the operation!"); 
  
    
  //需要推迟到子类(实现类) 中执行 
  protected abstract void operation(); 
 
  public void topOperation()
  
    beforeOperation(); 
 
    operation(); 
 
    afterOperation(); 
  
 
public class TempleteImpl extends Templete
  protected void operation()
  
    System.out.println("The operation action is executed in the method of ServiceA instance! "); 
  
 
public class TempletTest
  public static void main(String[] args)
  
    Templete templete = new TempleteImpl(); 
    templete.topOperation(); 
  

  

4.应用场景:

1) 一次性实现一个算法的不变的部分,并将可变的行为留给子类来实现。

2) 各子类中公共的行为应被提取出来并集中到一个公共父类中以避免代码重复。首先识别现有代码中的不同之处,并且将不同之处分离为新的操作。最后,用一个调用这些新的操作的模板方法来替换这些不同的代码。

1. 概念:定义一个算法的骨架,而将一些实现步骤延迟到子类中。

    把不变的行为搬到超类,去除子类中重复的代码来体现他的优势。

2. UML图:

Java之模板方法模式(Template Method)
    





            
Java之模板方法模式(Template Method)

3.代码:

public abstract class Templete
  private void beforeOperation()
  
    System.out.println("This acton before the operation!"); 
  
    
  private void afterOperation()
  
    System.out.println("This acton after the operation!"); 
  
    
  //需要推迟到子类(实现类) 中执行 
  protected abstract void operation(); 
 
  public void topOperation()
  
    beforeOperation(); 
 
    operation(); 
 
    afterOperation(); 
  
 
public class TempleteImpl extends Templete
  protected void operation()
  
    System.out.println("The operation action is executed in the method of ServiceA instance! "); 
  
 
public class TempletTest
  public static void main(String[] args)
  
    Templete templete = new TempleteImpl(); 
    templete.topOperation(); 
  

  

4.应用场景:

1) 一次性实现一个算法的不变的部分,并将可变的行为留给子类来实现。

2) 各子类中公共的行为应被提取出来并集中到一个公共父类中以避免代码重复。首先识别现有代码中的不同之处,并且将不同之处分离为新的操作。最后,用一个调用这些新的操作的模板方法来替换这些不同的代码。

相关文章:

  • 2021-07-03
  • 2021-12-29
  • 2021-08-24
  • 2021-10-11
  • 2021-10-04
  • 2022-12-23
猜你喜欢
  • 2022-03-07
  • 2021-09-08
  • 2021-09-10
  • 2022-02-23
  • 2021-07-24
  • 2021-05-10
相关资源
相似解决方案