標籤:原廠模式 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)