模板模式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
呵呵~ 簡單吧~