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

 模板模式Template概述:

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

2、抽象模板角色:

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

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

3、具體模板角色:

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

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

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

....

 

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

  1. package Template; 
  2. /** 
  3.  *@Description: 模板模式 
  4.  *<a href="http://my.oschina.net/arthor" class="referer" target="_blank">@author</a>  http://www.hualai.net.cn    
  5.  *@date 2012-08-17 
  6.  *@version V1.0    
  7.  */ 
  8. public class App { 
  9.  
  10. public static void main(String[] args) { 
  11. Pillar pillar=new CirclePillar(103); 
  12. System.out.println("pillar's V="+pillar.getBulk()); 

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

  1. package Template; 
  2. /** 
  3.  *@Description: 柱子(圓形柱和矩形柱)抽象類 
  4.  *<a href="http://my.oschina.net/arthor" class="referer" target="_blank">@author</a>  http://www.hualai.net.cn    
  5.  *@date 2012-08-17 
  6.  *@version V1.0    
  7.  */ 
  8. public abstract class Pillar{ 
  9. private float hight; 
  10.  
  11. public Pillar(float hight) { 
  12. this.hight = hight; 
  13.  
  14. /**獲得體積**/ 
  15. public double getBulk(){ 
  16. return getUnderArea()*hight; 
  17.  
  18. protected abstract float getUnderArea(); 

 

圓柱類:

  1. package Template; 
  2. /** 
  3.  *@Description: 圓柱 
  4.  *<a href="http://my.oschina.net/arthor" class="referer" target="_blank">@author</a>  http://www.hualai.net.cn    
  5.  *@date 2012-08-17 
  6.  *@version V1.0    
  7.  */ 
  8. public class CirclePillar extends Pillar { 
  9. private float r; 
  10.  
  11. public CirclePillar(float hight,float r){ 
  12. super(hight); 
  13. this.r=r; 
  14.  
  15. @Override 
  16. public float getUnderArea() { 
  17. // TODO Auto-generated method stub 
  18. return  (float) (Math.PI*r*r); 

 

矩形柱類:
  1. package Template; 
  2. /** 
  3.  *@Description:矩形柱 
  4.  *<a href="http://my.oschina.net/arthor" class="referer" target="_blank">@author</a>  http://www.hualai.net.cn    
  5.  *@date 2012-08-17 
  6.  *@version V1.0    
  7.  */ 
  8. public class RectPillar extends Pillar { 
  9. private float length; 
  10. private float width; 
  11.  
  12. public RectPillar(float hight,float length,float width) { 
  13. super(hight); 
  14. this.length=length; 
  15. this.width=width; 
  16.  
  17. @Override 
  18. public float getUnderArea() { 
  19. return length*width; 

 

打印結果:

  1. pillar's V=282.74334716796875 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章