1. 程式人生 > 其它 >C++_簡單工廠模式_程式碼案例

C++_簡單工廠模式_程式碼案例

#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(string
flag) { if (flag == "apple") { return new CApple; } else if (flag == "banana") { return new CBanana; } else if (flag == "pear") { return new CPear; } else { return
nullptr; } } }; 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; }