常见设计形式之【模板模式】
常见设计模式之【模板模式】 .
模板模式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; } @Override public float getUnderArea() { // TODO Auto-generated method stub return (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; } @Override public float getUnderArea() { return length*width; } }
打印结果:
pillar's V=282.74334716796875
呵呵~ 简单吧~