創建型模式之 抽象工廠模式
阿新 • • 發佈:2018-03-01
實現類 blog 教程 例子 UC 生成器 factory 生成 ...
介紹參見菜鳥教程
下面給出C++的一個例子
#include<iostream> #include<memory> using namespace std; //shap接口 class shap { public: virtual void draw() {}; }; //shap接口的實現類 class Rect : public shap { public: void draw() { std::cout << "生成一個矩形" << std::endl; } }; class Squ : public shap { public: void draw() { std::cout << "生成一個正方形" << std::endl; } }; class Circ : public shap { public: void draw() { std::cout << "生成一個圓" << std::endl; } }; //color接口 class color { public: virtual void fill() {}; }; //color 實現類 class Red : public color { public: void fill() { std::cout << "填充紅色" << std::endl; } }; class Green : public color { public: void fill() { std::cout << "填充綠色" << std::endl; } }; class Blue : public color { public: void fill() { std::cout << "填充藍色" << std::endl; } }; //為 Color 和 Shape 對象創建抽象類來獲取工廠 class AbstractFactory { public: virtual color* GetColor(string strColor) { return 0; }; virtual shap* GetShap(string strShap) { return 0; }; }; //創建shap工廠 class ShapFactory : public AbstractFactory { public: ShapFactory() { cShap = NULL; } ~ShapFactory() { ReleaseFactouy(); } shap* GetShap(string strShap) { if (strShap.compare("rectangle") == 0) { cShap = new Rect; } if (strShap.compare("square") == 0) { cShap = new Squ; } if (strShap.compare("circle") == 0) { cShap = new Circ; } return cShap; } void ReleaseFactouy() { if (cShap != NULL) { delete cShap; } } private: shap * cShap; }; //創建色彩工廠 class ColorFactory : public AbstractFactory { public: ColorFactory() { cColor = NULL; } ~ColorFactory() { ReleaseFactouy(); } color* GetColor(string strColor) { if (strColor.compare("red") == 0) { cColor = new Red; } if (strColor.compare("green") == 0) { cColor = new Green; } if (strColor.compare("blue") == 0) { cColor = new Blue; } return cColor; } void ReleaseFactouy() { if (cColor != NULL) { delete cColor; } } private: color * cColor; }; //創建一個工廠創造器/生成器類,通過傳遞形狀或顏色信息來獲取工廠 class FactroyProduce { private: FactroyProduce() {}; ~FactroyProduce() {}; int i; public: static AbstractFactory* GetFactory(string strFact) { if (strFact.compare("shap") == 0 ) { cout << "新的mew1" << endl; return new ShapFactory; } else if (strFact.compare("color") == 0) { cout << "新的mew2" << endl; return new ColorFactory; } else { return NULL; } } }; int main() { shared_ptr<AbstractFactory> AbsFact(FactroyProduce::GetFactory("shap")); shap* shap1 = AbsFact->GetShap("rectangle"); shap1->draw(); //生成一個矩形 //... shared_ptr<AbstractFactory> AbsFact2(FactroyProduce::GetFactory("color")); color* color1 = AbsFact2->GetColor("red"); color1->fill(); //生成紅色 //... return 0; }
創建型模式之 抽象工廠模式