Abstract Factory Pattern (Abstract Factory): Provides an interface for creating a series of related or interdependent objects without specifying their specific classes.
Pattern implementation:
[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; } }
Client:
[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; }
The above is the content of the abstract factory pattern of C++ design patterns. For more related content, please pay attention to the PHP Chinese website (www .php.cn)!