Factory,工廠設計模式,C++描述

來源:互聯網
上載者:User

標籤:col   head   pdf   c51   asm   new   DRC   xsl   gimp   

常見設計模式的解析和實現(C++)之一-Factory 模式  作用:
定義一個用於建立對象的介面,讓子類決定執行個體化哪一個類。Factory Method使一個類的執行個體化延遲到其子類 
抽象基類: 1) Product:建立出來的對象的抽象基類. 2) Factory 建立對象的Factory 方法的抽象基類. 介面函數: 1) Creator::FactoryMethod:純虛函數,由衍生類別實現,建立出對應的 Product. 解析: 在這個模式中,有兩個抽象基類,一個是 Product 為建立出來的對象的抽象基類,一個是 Factory 是工廠的抽象基類,在互相協作的時候都是由相應的 Factory 派生類來產生Product的衍生類別,也就是說如果要新增一種Product那麼也要對應的新增一個 Factory,建立的過程委託給了這個 Factory.也就是說一個 Factory和一個 Product 是一一對應的關係. 備忘: 設計模式的示範圖上把Factory類命名為Creator,下面的實現沿用了這個命名.
#ifndef __FACTORY_H__ #define __FACTORY_H__ #include<iostream> using namespace std; class product {         public:                 product(){  cout<<"product()"<<endl;  }                 virtual ~product(){  cout<<"~product()"<<endl;  } }; class A {         public:                 A(){  cout<<"A()"<<endl;  }                 ~A(){  cout<<"~A()"<<endl;  } }; class B {         public:                 B(){  cout<<"B()"<<endl;  }                 ~B(){  cout<<"~B()"<<endl;  } }; class concreteproduct:public product {         public:                 concreteproduct(A* pa,B* pb):_pa(pa),_pb(pb)                 {                         cout<<"concreteproduct()"<<endl;                  }                 ~concreteproduct(){  cout<<"~concreteproduct()"<<endl;  }         private:                 A* _pa;                 B* _pb; }; class factory {         public:                 factory(){  cout<<"factory()"<<endl;  }                 // 抽象類別                 virtual product* create() = 0;                 virtual ~factory(){  cout<<"~factory()"<<endl;  } }; class concretefactory:public factory {         public:                 concretefactory(){  cout<<"concretefactory()"<<endl;  }                 product* create();                 ~concretefactory(){  cout<<"~concretefactory()"<<endl;  } }; product* concretefactory::create() {         cout<<"concretefactory::create()"<<endl;         A* pa = new A();         B* pb = new B();         product* pro = new concreteproduct(pa,pb);         return pro; } endif #include<iostream> #include"factory.h" using namespace std; int main() { // 原廠模式主要用來建立複雜物件   // 一個產品對應一個工廠類         factory* fac = new concretefactory();         product* pro = fac->create();         delete fac;         delete pro;         return 0; }

 
 



Factory,工廠設計模式,C++描述

聯繫我們

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