Java Q&A: 使用Factory Method模式(轉)

來源:互聯網
上載者:User
Java Q&A: 使用Factory Method模式
Q: 閱讀 "Polymorphism in its purest form" 一文時,我看到了一個不熟悉的術語 "Factory method"。你能解釋一下什麼是Factory method並說明如何使用它嗎?
A: Factory method(Factory 方法)只不過是執行個體化對象的一種方法的名稱。就象工廠一樣,Factory method的任務是建立--或製造--對象。
讓我們看一個例子。
每個程式要有一種報錯的方式。看看下面的介面:
代碼清單1
public interface Trace {
      // turn on and off debugging
      public void setDebug( boolean debug );
      // write out a debug message
      public void debug( String message );
      // write out an error message
      public void error( String message );
}
假設寫了兩個實現。一個實現(代碼清單3)將資訊寫到命令列,另一個(代碼清單2)則寫到檔案中。
代碼清單2
public class FileTrace implements Trace {

      private java.io.PrintWriter pw;
      private boolean debug;
      public FileTrace() throws java.io.IOException {
            // a real FileTrace would need to obtain the filename somewhere
            // for the example I'll hardcode it
            pw = new java.io.PrintWriter( new java.io.FileWriter( "c:race.log" ) );
      }
      public void setDebug( boolean debug ) {
            this.debug = debug;
      }
      public void debug( String message ) {

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.