Abstract Factory-Muster (Abstract Factory): Bietet eine Schnittstelle zum Erstellen einer Reihe verwandter oder voneinander abhängiger Objekte, ohne deren spezifische Klassen anzugeben.
Musterimplementierung:
[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; } }
Kunde:
[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; }
Das Obige ist der Inhalt einer kurzen Einführung in das abstrakte Fabrikmuster in C++-Entwurfsmustern Verwandte Inhalte, achten Sie bitte auf die chinesische PHP-Website (www.php.cn)!