c++库设计模式设计模式 BY C++

【C++ 设计模式】1-1.简单工厂模式

2019-10-12  本文已影响0人  JeremyYv


以下是简单工厂模式的简易代码实现
// SimpleFactory.hpp
#include <iostream>
using namespace std;

// 枚举定义产品类型
typedef enum ProductType {
    DESK,
    CHAIR,
} PROTYPE;

// 产品抽象类
class Product {
public:
    virtual void Show() = 0; // 用于验证产品信息
};

class WoodDesk: public Product {
public: 
    void Show() {
        cout << "WoodDesk" << endl;
    }
};

class WoodChair : public Product {
public:
    void Show() {
        cout << "WoodChair" << endl;
    }
};

// 工厂类
class Factory {
public:
    Product* CreateProduct(PROTYPE type) {
        switch (type) {
        case Desk:
            return new WoodDesk();
        case Chair:
            return new WoodChair();
        default:
            break;
        }
        return NULL;
    }
};
主函数中的使用
// main.c
#include "SimpleFactory.hpp"

int main()
{
    // 创建工厂
    Factory* MyFactory = new Factory();

    // 传入产品类型创建产品
    Product* DeskWood = MyFactory->CreateProduct(Desk);
    DeskWood->Show();
    Product* ChairWood = MyFactory->CreateProduct(Chair);
    ChairWood->Show();
 
    if (NULL != MyFactory) {
        delete MyFactory;
        MyFactory = NULL;
    }
    return 0;
}
控制台输出结果
WoodDesk
WoodChair

上一篇下一篇

猜你喜欢

热点阅读