《設計模式精解》學習筆記(十四)------Template Method(模板方法)模式

來源:互聯網
上載者:User

《設計模式精解》學習筆記(十四)------Template Method(模板方法)模式

 

GOF定義一個操作中的演算法的骨架,而將一些步驟延遲到子類中。Template Method使得子類可以不改變一個演算法的結構即可以重定義該演算法的某些特定步驟。

 

繼承是OO思想的三大特性(封裝、繼承、多態)之一。繼承是為了更好的代碼重用,但是在今天,越來越多的OO方法學大師都不止在一處的總結出:要優先運用組合而不是繼承。Template Method模式是目前學到的最簡單的模式之一。這也是比較常用到的模式。在Template Method模式中就充分運用了繼承。其實在我看來,Template Method模式就是繼承。在一個畫圖的程式中,我寫了一個叫drow的方法,它將畫出我需要的圖形。Template Method模式可以幫我做到這一點,因為對方法的調用通過一個引用來進行的,而這個引用指向的對象屬於某一個衍生類別。

 

下面是Template Method模式UML圖:

 

 

下面是實現的Java代碼:

定義一個抽象類別,用來定義某演算法的骨架,在這裡是abstract drow。

package TemplateMethod;

 

public abstract class ShapeTemplate

{

       public abstract void drow();//Template Method

}//end abctract class shape

 

package TemplateMethod;

 

派生出一個具體類,在具體類中實現了方法drow。

public class Square extends ShapeTemplate

{

       @Override

       public void drow()

       {

              System.out.println("畫出正方形");

       }//end drow()

 

}//end class Square

 

package TemplateMethod;

 

測試代碼:

public class TemplateMethodPattern

{

      

       private ShapeTemplate square;

 

       public TemplateMethodPattern()

       {

              square = new Square();

       }//end TemplateMethodPattern()

      

       public void showTemplateMethodPattern()

       {

              square.drow();

       }//end showTemplateMethodPattern()

      

       public static void main(String[] args)

       {

              System.out.println("The Template Method Pattern!");

             

              TemplateMethodPattern tmp = new TemplateMethodPattern();

              tmp.showTemplateMethodPattern();

       }//end main(...)

 

}//end class TemplateMethodPattern

 

運行結果:

The Template Method Pattern!

畫出正方形

 

Template Method模式讓我們可以先定義這些步驟地順序,然後重載那些需要改變的步驟。  

Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=954056  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.