模板模式Template概述:
1、定義一個操作中算法的骨架,將一些步驟的執行延遲到其子類中。
2、抽象模板角色:
①定義了一個或者多個抽象操作,以便讓其子類實現
②定義並實現一個模板方法。
3、具體模板角色:
①實現父類所定義的一個或者多個抽象方法
②可以有任意多個具體模板角色,實現同一個抽象模板角色
③每一個具體模板角色都可以給出這些抽象方法的不同實現。
....
其實我不太喜歡把這些東西擺上去。來上傳一個我簡寫的demo
- package Template;
- /**
- *@Description: 模板模式
- *<a href="http://my.oschina.net/arthor" class="referer" target="_blank">@author</a> http://www.hualai.net.cn
- *@date 2012-08-17
- *@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: 柱子(圓形柱和矩形柱)抽象類
- *<a href="http://my.oschina.net/arthor" class="referer" target="_blank">@author</a> http://www.hualai.net.cn
- *@date 2012-08-17
- *@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: 圓柱
- *<a href="http://my.oschina.net/arthor" class="referer" target="_blank">@author</a> http://www.hualai.net.cn
- *@date 2012-08-17
- *@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:矩形柱
- *<a href="http://my.oschina.net/arthor" class="referer" target="_blank">@author</a> http://www.hualai.net.cn
- *@date 2012-08-17
- *@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