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


1. 概念:定義一個算法的骨架,而將一些實現步驟延遲到子類中。

    把不變的行為搬到超類,去除子類中重復的代碼來體現他的優勢。

2. UML圖:

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) 各子類中公共的行為應被提取出來並集中到一個公共父類中以避免代碼重復。首先識別現有代碼中的不同之處,並且將不同之處分離為新的操作。最后,用一個調用這些新的操作的模板方法來替換這些不同的代碼。

 --------------------------------------------------------------------

PS: 歡迎關注公眾號"Devin說",會不定期更新Java相關技術知識。

--------------------------------------------------------------------


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM