借鑒于:C++設(shè)計(jì)模式——抽象工廠模式
#include <iostream>using namespace std;/*typedef enum PRoductTypeTag{}PRODUCTTYPE;*/enum ProductTypeTag { TypeA, TypeB, TypeC};typedef enum ProductTypeTag PRODUCTTYPE;//一個(gè)純虛函數(shù),一個(gè)純虛基類class Product{public: virtual void show() = 0;};//以下有由兩個(gè)產(chǎn)品class ProductA : public Product{public: void show() { cout << "I'm Product A" << endl; }};class ProductB : public Product{public: void show() { cout << "I'm Product B" << endl; }};//下面要?jiǎng)?chuàng)建一個(gè)工廠類class Factory{public: Product * CreateProduct(PRODUCTTYPE type) { switch(type) { case TypeA: return new ProductA(); case TypeB: return new ProductB(); default: return 0; } }};void deleteAndPoint0 (void * obj){ delete obj; obj = 0; cout << "delete " << endl;}int main(){// cout << "Hello World!" << endl; //First ,create a factory object Factory *factory = new Factory(); Product * productObjA = factory->CreateProduct(TypeA); if (productObjA != 0) { productObjA->show(); } Product *productObjB = factory->CreateProduct(TypeB); if (productObjB != 0) { productObjB->show(); } deleteAndPoint0(factory); deleteAndPoint0(productObjA); deleteAndPoint0(productObjB); return 0;}/* * 以上為簡單的工程模式,后面還有變更的 工廠方法模式 和 抽象工廠模式 * 至于工廠方法模式即:如果后續(xù)需要添加新的產(chǎn)品時(shí),就要修改源碼,這是大忌。 * 所以,就把工廠給作為抽象類。然后,如果新來一個(gè)產(chǎn)品,我就開一條流水線,專一生產(chǎn)這種產(chǎn)品。 * 以下為工廠類的編碼。**/class Factory{public: virtual Product *CreateProduct() = 0;};class FactoryA : public Factory{public: Product *CreateProduct() { return new ProductA (); }};class FactoryB : public Factory{public: Product *CreateProduct() { return new ProductB (); }};/* * 還有一種情況:就是當(dāng)產(chǎn)品過多是,一個(gè)產(chǎn)品對應(yīng)一個(gè)產(chǎn)品類。就會(huì)把問題給復(fù)雜化,這樣就出現(xiàn)了第三種衍變:抽象工廠模式 * 在這種方式中:把工廠和產(chǎn)品都進(jìn)行了抽象。 * 通過把工廠進(jìn)行整合,使抽象工廠中可以生產(chǎn)兩種產(chǎn)品,例如 A 和 B。 * 而繼承工廠的工廠1,則可以生產(chǎn)就有A 和 B 相似的產(chǎn)品。C 和 D * 而繼承工廠的工廠2,則可以生產(chǎn)與 C,D不同,但繼承與A B 的產(chǎn)品 E F。**/class ProductA{public: virtual void Show() = 0;};class ProductA1 : public ProductA{public: void Show() { cout<<"I'm ProductA1"<<endl; }};class ProductA2 : public ProductA{public: void Show() { cout<<"I'm ProductA2"<<endl; }};// Product Bclass ProductB{public: virtual void Show() = 0;};class ProductB1 : public ProductB{public: void Show() { cout<<"I'm ProductB1"<<endl; }};class ProductB2 : public ProductB{public: void Show() { cout<<"I'm ProductB2"<<endl; }};// Factoryclass Factory{public: virtual ProductA *CreateProductA() = 0; virtual ProductB *CreateProductB() = 0;};class Factory1 : public Factory{public: ProductA *CreateProductA() { return new ProductA1(); } ProductB *CreateProductB() { return new ProductB1(); }};class Factory2 : public Factory{ ProductA *CreateProductA() { return new ProductA2(); } ProductB *CreateProductB() { return new ProductB2(); }};//這樣在新增產(chǎn)品時(shí),避免工廠的多而管理困難的問題。新聞熱點(diǎn)
疑難解答