C++_簡單工廠模式_程式碼案例
阿新 • • 發佈:2021-07-24
#include <iostream> using namespace std; // 水果抽象類 class CAbstractFruit { public: virtual void ShowName() = 0; }; // 蘋果類 class CApple : public CAbstractFruit { public: virtual void ShowName() { cout << " 我是蘋果!" << endl; } }; // 香蕉類 class CBanana : public CAbstractFruit {public: virtual void ShowName() { cout << " 我是香蕉!" << endl; } }; // 鴨梨類 class CPear : public CAbstractFruit { public: virtual void ShowName() { cout << " 我是鴨梨!" << endl; } }; // 水果工廠類 class CFruitFactory { public: static CAbstractFruit* CreateFruit(stringflag) { if (flag == "apple") { return new CApple; } else if (flag == "banana") { return new CBanana; } else if (flag == "pear") { return new CPear; } else { returnnullptr; } } }; int main() { CAbstractFruit* fruit = CFruitFactory::CreateFruit("apple"); if (fruit != nullptr) { fruit->ShowName(); } delete fruit; fruit = CFruitFactory::CreateFruit("banana"); if (fruit != nullptr) { fruit->ShowName(); } delete fruit; fruit = CFruitFactory::CreateFruit("pear"); if (fruit != nullptr) { fruit->ShowName(); } delete fruit; cin.get(); return 0; }