Java設計模式-抽象原廠模式(Abstract Factory)

來源:互聯網
上載者:User

標籤:原廠模式   java設計模式   設計模式   

目的:提供一個介面來建立一族相互依賴的對象,不用明確指出實體類。

什麼時候用:
  • 一個系統不應當依賴於產品類執行個體如何被建立、組合和表達的細節,這對於所有形態的原廠模式都是重要的。
  • 這個系統的產品有多於一個的產品族,而系統只消費其中某一族的產品。
  • 同屬於同一個產品族的產品是在一起使用的,這一約束必須在系統的設計中體現出來。
  • 系統提供一個產品類的庫,所有的產品以同樣的介面出現,從而使用戶端不依賴於實現。
實際的例子:
  • javax.xml.parsers.DocumentBuilderFactory
範例程式碼:
public class App {public static void main(String[] args) {createKingdom(new ElfKingdomFactory());createKingdom(new OrcKingdomFactory());}public static void createKingdom(KingdomFactory factory) {King king = factory.createKing();Castle castle = factory.createCastle();Army army = factory.createArmy();System.out.println("The kingdom was created.");System.out.println(king);System.out.println(castle);System.out.println(army);}}
public interface King {}public interface Castle {}public interface Army {}public interface Army {}
<pre name="code" class="java">public interface KingdomFactory {Castle createCastle();King createKing();Army createArmy();}

public class ElfKingdomFactory implements KingdomFactory {public Castle createCastle() {return new ElfCastle();}public King createKing() {return new ElfKing();}public Army createArmy() {return new ElfArmy();}}
public class OrcKingdomFactory implements KingdomFactory {public Castle createCastle() {return new OrcCastle();}public King createKing() {return new OrcKing();}public Army createArmy() {return new OrcArmy();}}
public class ElfArmy implements Army {@Overridepublic String toString() {return "This is the Elven Army!";}}
public class ElfKing implements King {@Overridepublic String toString() {return "This is the Elven king!";}}
public class ElfCastle implements Castle {@Overridepublic String toString() {return "This is the Elven castle!";}}
public class OrcArmy implements Army {@Overridepublic String toString() {return "This is the Orcish Army!";}}
public class OrcCastle implements Castle {@Overridepublic String toString() {return "This is the Orcish castle!";}}
public class OrcKing implements King {@Overridepublic String toString() {return "This is the Orc king!";}}

輸出結果:
The kingdom was created.This is the Elven king!This is the Elven castle!This is the Elven Army!The kingdom was created.This is the Orc king!This is the Orcish castle!This is the Orcish Army!

@鬥大的熊貓












Java設計模式-抽象原廠模式(Abstract Factory)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.