設計模式之原廠模式學習筆記(續)

來源:互聯網
上載者:User

 上一篇學習了原廠模式的簡單工廠和Factory 方法,現在繼續學習原廠模式的第三種形態:抽象工廠,前面我們的學習的原廠模式都是一個工廠建立一個產品,但如果需要一個工廠建立多個產品的話,就需要我們學習抽象原廠模式了,其實基本原理還是和Factory 方法類似的,只不過將抽象工廠類放入了更多需要具體工廠實現的產品介面而已,下面用例子來說明。

 

抽象產品ProductA

  1. public interface ProductA {
  2. }

抽象產品ProductB

  1. public interface ProductB {
  2. }

具體產品ProductA1

  1. public class ProductA1 implements ProductA {
  2.     public ProductA1() {
  3.         System.out.println("create ProductA1");
  4.     }
  5. }

具體產品ProductA2

  1. public class ProductA2 implements ProductA {
  2.     public ProductA2() {
  3.         System.out.println("create ProductA2");
  4.     }
  5. }

具體產品ProductB1

  1. public class ProductB1 implements ProductB {
  2.     public ProductB1() {
  3.         System.out.println("create ProductB1");
  4.     }
  5. }

具體產品ProductB2

  1. public class ProductB2 implements ProductB {
  2.     public ProductB2() {
  3.         System.out.println("create ProductB2");
  4.     }
  5. }

抽象工廠類

  1. public interface AbstractFactory {
  2.     public ProductA createProductA();
  3.     public ProductB createProductB();
  4. }

具體工廠類FactoryA

  1. public class FactoryA implements AbstractFactory {
  2.     public ProductA createProductA() {
  3.         // TODO Auto-generated method stub
  4.         return new ProductA1();
  5.     }
  6.     public ProductB createProductB() {
  7.         // TODO Auto-generated method stub
  8.         return new ProductB1();
  9.     }
  10. }

具體工廠類FactoryB

  1. public class FactoryB implements AbstractFactory {
  2.     public ProductA createProductA() {
  3.         // TODO Auto-generated method stub
  4.         return new ProductA2();
  5.     }
  6.     public ProductB createProductB() {
  7.         // TODO Auto-generated method stub
  8.         return new ProductB2();
  9.     }
  10. }

用戶端應用

  1. public class FactoryDemo3 {
  2.     public static void main(String[] args) {
  3.         AbstractFactory af = new FactoryA();
  4.         ProductA pa1 = af.createProductA();
  5.         ProductB pa2 = af.createProductB();
  6.     }
  7. }

結果將返回:

create ProductA1
create ProductB1

 

說明具體工廠的確具備了建立兩個產品的能力。

 

 

聯繫我們

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