常見設計模式之【模板模式】

來源:互聯網
上載者:User

模板模式Template概述:

1、定義一個操作中演算法的骨架,將一些步驟的執行延遲到其子類中。

2、抽象模板角色:

      ①定義了一個或者多個抽象操作,以便讓其子類實現

      ②定義並實現一個模板方法。

3、具體模板角色:

      ①實現父類所定義的一個或者多個抽象方法

      ②可以有任意多個具體模板角色,實現同一個抽象模板角色

      ③每一個具體模板角色都可以給出這些抽象方法的不同實現。

....

其實我不太喜歡把這些東西擺上去。來上傳一個我簡寫的demo

package Template;/** *@Description: 模板模式 *@author Potter    *@date 2012-8-16 下午11:04:38 *@version V1.0    */public class App {public static void main(String[] args) {Pillar pillar=new CirclePillar(10, 3);System.out.println("pillar's V="+pillar.getBulk());}}

柱子(圓形柱和矩形柱)抽象類別

package Template;/** *@Description: 柱子(圓形柱和矩形柱)抽象類別 *@author Potter    *@date 2012-8-16 下午10:50:13 *@version V1.0    */public abstract class Pillar{private float hight;public Pillar(float hight) {this.hight = hight;}/**獲得體積**/public double getBulk(){return getUnderArea()*hight;}protected abstract float getUnderArea();}

圓柱類:

package Template;/** *@Description: 圓柱 *@author Potter    *@date 2012-8-16 下午10:57:21 *@version V1.0    */public class CirclePillar extends Pillar {private float r;public CirclePillar(float hight,float r){super(hight);this.r=r;}@Overridepublic float getUnderArea() {// TODO Auto-generated method stubreturn  (float) (Math.PI*r*r);}}

矩形柱類:

package Template;/** *@Description:矩形柱 *@author Potter    *@date 2012-8-16 下午11:01:52 *@version V1.0    */public class RectPillar extends Pillar {private float length;private float width;public RectPillar(float hight,float length,float width) {super(hight);this.length=length;this.width=width;}@Overridepublic float getUnderArea() {return length*width;}}

列印結果:

pillar's V=282.74334716796875

 

呵呵~  簡單吧~  

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.