抽象工厂模式(Abstract Factory):提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
模式实现:
[code]//create ProductA class ProductA{ public: virtual void Show() = 0; }; class ProductA1: public ProductA{ public: void Show(){ std::cout << "I'm ProductA1\n"; } }; class ProductA2: public ProductA{ public: void Show(){ std::cout << "I'm ProductA2\n"; } }; //create ProductB class ProductB{ public: virtual void Show() = 0; }; class ProductB1: public ProductB{ public: void Show(){ std::cout << "I'm ProductB1\n"; } }; class ProductB2: public ProductB{ public: void Show(){ std::cout << "I'm ProductB2\n"; } }; class 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{ public: ProductA *CreateProductA(){ return new ProductA2(); } ProductB *CreateProductB(){ return new ProductB2(); } }; template <typename T> void del(T* obj){ if( obj != NULL){ delete obj; obj = NULL; } }
客户端:
[code]int main(){ Factory *factoryObj1 = new Factory1(); ProductA *productObjA1 = factoryObj1->CreateProductA(); ProductB *productObjB1 = factoryObj1->CreateProductB(); productObjA1->Show(); //Output: I'm ProductA1 productObjB1->Show(); //Output: I'm ProductB1 Factory *factoryObj2 = new Factory2(); ProductA *productObjA2 = factoryObj2->CreateProductA(); ProductB *productObjB2 = factoryObj2->CreateProductB(); productObjA2->Show(); //Output:I'm ProductA2 productObjB2->Show(); //Output:I'm ProductB2 del(productObjB2); del(productObjA2); del(factoryObj2); del(productObjB1); del(productObjA1); del(factoryObj1); return 0; }
以上就是C++设计模式浅识抽象工厂模式的内容,更多相关内容请关注PHP中文网(www.php.cn)!