設計模式--抽象原廠模式

來源:互聯網
上載者:User

標籤:nts   static   img   exception   package   string   oid   throws   pat   

抽象原廠模式(Abstract Factory Pattern)

定義:為建立一組相關或相互依賴的對象提供一個介面,而且無需指定他們的具體類。

類型:建立型模式

類圖:

 

代碼實現:

首先給出產品族,也就是類圖中右半部分

package zwb;interface ProductA {    void methodA();}interface ProductB {    void methodB();}class ProductA1 implements ProductA{    public void methodA() {        System.out.println("產品A系列中1型號產品的方法");    } }class ProductA2 implements ProductA{    public void methodA() {        System.out.println("產品A系列中2型號產品的方法");    }}class ProductB1 implements ProductB{    public void methodB() {        System.out.println("產品B系列中1型號產品的方法");    }}class ProductB2 implements ProductB{    public void methodB() {        System.out.println("產品B系列中2型號產品的方法");    } }

下面是類圖中左半部分,首先給出工廠介面

package zwb;public interface Creator {    ProductA createProductA();        ProductB createProductB();    }

下面是兩個具體的工廠實作類別

package zwb;public class ConcreteCreator1 implements Creator{    public ProductA createProductA() {        return new ProductA1();    }    public ProductB createProductB() {        return new ProductB1();    }}
package zwb;public class ConcreteCreator2 implements Creator{    public ProductA createProductA() {        return new ProductA2();    }    public ProductB createProductB() {        return new ProductB2();    }}

這樣類圖代碼實現完畢,下面寫一個測試類別,去調用一下,感受一下抽象原廠模式的用戶端調用方式

package zwb;public class Client {    public static void main(String[] args) throws Exception {        Creator creator = new ConcreteCreator1();        ProductA productA = creator.createProductA();        ProductB productB = creator.createProductB();        productA.methodA();        productB.methodB();                creator = new ConcreteCreator2();        productA = creator.createProductA();        productB = creator.createProductB();        productA.methodA();        productB.methodB();    }}

運行結果:

產品A系列中1型號產品的方法產品B系列中1型號產品的方法產品A系列中2型號產品的方法產品B系列中2型號產品的方法

Factory 方法模式和抽象原廠模式的區別:

Factory 方法模式:

  • 一個抽象產品類,可以派生出多個具體產品類。 
  • 一個抽象工廠類,可以派生出多個具體工廠類。 
  • 每個具體工廠類只能建立一個具體產品類的執行個體。

抽象原廠模式:

  • 多個抽象產品類,每個抽象產品類可以派生出多個具體產品類。 
  • 一個抽象工廠類,可以派生出多個具體工廠類。 
  • 每個具體工廠類可以建立多個具體產品類的執行個體。 

區別:
  Factory 方法模式只有一個抽象產品類,而抽象原廠模式有多個。 
  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.