設計模式之模版方法Template Method Pattern

Template Method Pattern,父類指定處理大綱,子類規定具體內容的設計模式叫做模版方法模式。

下面的示例是反覆輸出5次同一個字符或字符串。

                                                                 表3-1 類一覽表
名稱 說明
AbstractDisplay 只是現方法display的抽象類
CharDisplay 實現方法open,print,close的類
StringDisplay 實現方法open,print,close的類
Main 測試類

AbstractDisplay 抽象類
  1. public abstract class AbstractDisplay {   
  2.   public abstract  void open();   
  3.   public abstract  void print();   
  4.   public abstract  void close();   
  5.   public final void display() {   
  6.      open();   
  7.      forint i=0;i<5;i++)   
  8.      {  print(); }   
  9.      close();   
  10.   }   
  11. }  
CharDispaly類
  1. public class CharDisplay extends AbstractDisplay {           
  2.   private char ch;           
  3.   public CharDisplay(char ch) {           
  4.      this.ch = ch;           
  5.    }           
  6.   public void open() {           
  7.     System.out.print("××");           
  8.   }           
  9.   public void print() {           
  10.    System.out.print(ch);           
  11.    }           
  12.   public void close() {           
  13.     System.out.print("××");           
  14.   }           
  15. }        
StringDispaly 類
  1. public class StringDisplay extends AbstractDisplay { //他也是AbstractDisplay的子類   
  2.   private String string;   
  3.   private int width;   
  4.   public StringDisplay(String string) {   
  5.     this.string = string;   
  6.     this.width = string.getBytes().length; }   
  7.   public void open() {   
  8.     printLine();  //此方法畫線段   
  9.   }   
  10.   public void print() {   
  11.     System.out.print("|"+string+"|");   
  12.    }   
  13.   public void close() {   
  14.      printLine(); }   
  15.   private void printLine() {   
  16.      System.out.print("+");   
  17.      for(int i = 0 ;i < width ; i++) {   
  18.        System.out.print("--");   
  19.      }   
  20.   System.out.println("+");   
  21. }  }  
Main測試類
  1. public class Main  {   
  2.    public static void main(String[] args) {   
  3.      AbstractDisplay  d1 = new CharDisplay('H');   
  4.      AbstractDisplay  d2 = new StringDisplay("Hello,World!");   
  5.     d1.display();   
  6.     d2.display();   
  7.    }   
  8. }  
發佈了1 篇原創文章 · 獲贊 0 · 訪問量 3916
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章