C++設計模式學習筆記03_抽象工廠1
阿新 • • 發佈:2018-12-13
0 抽象工廠
1、接著上次總結,前面提到當需要生產一個新的產品(和舊產品存在某種聯絡)但是不希望新建一個工廠,而是在舊的工廠中加入一個新的生產線,需要引入抽象工廠模式
2、抽象工廠模式和工廠方法模式類似,區別在於
a、產品類增加了不同基類,不同基類下派生不同產品
b、工廠不增加基類,但是在每個工廠中增加純虛擬函式(相當於工廠中增加生產線)
3、在具體生產產品時,先選擇工廠,在選擇工廠中的生產線即可
#include <iostream> using namespace std; class ProductA { public: virtual void ShowYouself() = 0; private: }; class ProductA1 : public ProductA { public: void ShowYouself() { cout << "建立了A1" << endl; } private: }; class ProductA2 : public ProductA { public: void ShowYouself() { cout << "建立了A2" << endl; } private: }; //**************************ProtuctB******************************* class ProductB { public: virtual void ShowYouself() = 0; private: }; class ProductB1 : public ProductB { public: void ShowYouself() { cout << "建立了B1" << endl; } private: }; class ProductB2 : public ProductB { public: void ShowYouself() { cout << "建立了B2" << endl; } private: }; //**************************Fectory******************************** class Fectory { public: virtual ProductA *CreateProtectA() = 0; virtual ProductB *CreateProtectB() = 0; }; class Fectory1 : public Fectory { public: ProductA *CreateProtectA() { cout << "來到工廠1,這條生產線生產A1" << endl; return new ProductA1; } ProductB *CreateProtectB() { cout << "來到工廠1,這條生產線生產B1" << endl; return new ProductB1; } }; class Fectory2 : public Fectory { public: ProductA *CreateProtectA() { cout << "來到工廠2,這條線生產A2" << endl; return new ProductA2; } ProductB *CreateProtectB() { cout << "來到工廠2,這條線生產B2" << endl; return new ProductB2; } }; int main(void) { Fectory *fectory1 = new Fectory1(); Fectory *fectory2 = new Fectory2(); ProductA *productA1 = fectory1->CreateProtectA(); ProductB *productB1 = fectory1->CreateProtectB(); productA1->ShowYouself(); productB1->ShowYouself(); ProductA *productA2 = fectory2->CreateProtectA(); ProductB *productB2 = fectory2->CreateProtectB(); productA2->ShowYouself(); productB2->ShowYouself(); if (productA1 != NULL) { cout << "productA1被回收" << endl; delete productA1; productA1 = NULL; } if (productB1 != NULL) { cout << "productB1被回收" << endl; delete productB1; productB1 = NULL; } if (productA2 != NULL) { cout << "productA2被回收" << endl; delete productA2; productA2 = NULL; } if (productB2 != NULL) { cout << "productB2被回收" << endl; delete productB2; productB2 = NULL; } if (fectory1 != NULL) { cout << "fectory1被回收" << endl; delete fectory1; fectory1 = NULL; } if (fectory2 != NULL) { cout << "fectory2被回收" << endl; delete fectory2; fectory2 = NULL; } system("pause"); return 0; }