抽象原廠模式(Abstract Factory):提供一個建立一系列相關或相互依賴對象的介面,而無需指定它們具體的類。
模式實現:
[code]//create ProductAclass 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 ProductBclass 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++設計模式淺識抽象原廠模式的內容,更多相關內容請關注topic.alibabacloud.com(www.php.cn)!