1. 程式人生 > 其它 >C++ 工廠模式簡單實現

C++ 工廠模式簡單實現

//缺點:工廠類集中了所有產品類的建立邏輯,如果產品量較大,會使得工廠類變的非常臃腫。
#include <iostream> #include <string> using namespace std; class Cost{ public: virtual const string& color() = 0; }; class WhiteShit : public Cost{ public: WhiteShit():Cost(),m_color("white"){} const string& color(){ cout
<< m_color << endl; return m_color; } private: string m_color; }; class BlackShit : public Cost{ public: BlackShit():Cost(),m_color("black"){} const string& color(){ cout << m_color << endl; return m_color; } private
: string m_color; }; class Plant{ public: virtual const string& color() = 0; }; class WhitePlant : public Plant{ public: WhitePlant():Plant(),m_color("white"){} const string& color(){ cout << m_color << endl; return m_color; } private
: string m_color; }; class BlackPlant : public Plant{ public: BlackPlant():Plant(),m_color("black"){} const string& color(){ cout << m_color << endl; return m_color; } private: string m_color; }; class Factory{ public: virtual Cost *createCost() = 0; virtual Plant *createPlant() = 0; }; class WhiteFactory : public Factory{ public: Cost *createCost() override{ return new WhiteShit(); } Plant *createPlant() override{ return new WhitePlant(); } }; class BlackFactory : public Factory{ public: Cost *createCost() override{ return new BlackShit(); } Plant *createPlant() override{ return new BlackPlant(); } }; int main() { WhiteFactory factory; factory.createCost()->color(); factory.createPlant()->color(); BlackFactory factory1; factory1.createCost()->color(); factory1.createPlant()->color(); cout << "Hello, world!" << endl; return 0; }

參考:https://www.cnblogs.com/chengjundu/p/8473564.html