设计模式设计模式 BY C++程序员

【C++ 设计模式】1-2.工厂方法模式

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


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

// 产品抽象类
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:
    virtual Product* CreateProduct() = 0;
};

class DeskFactory: public Factory {
public:
    Product* CreateProduct() {
        return new WoodDesk();
    }
};

class ChairFactory : public Factory {
public:
    Product* CreateProduct() {
        return new WoodChair();
    }
};
主函数中的使用
#include "FactoryMethod.hpp"

int main()
{
    Factory* FactoryDesk = new DeskFactory();
    Product* DeskWood = FactoryDesk->CreateProduct();
    DeskWood->Show();
 
    Factory* FactoryChair = new ChairFactory();
    Product* ChairWood = FactoryChair->CreateProduct();
    ChairWood->Show();
 
    if (NULL != FactoryDesk) {
        delete FactoryDesk;
        FactoryDesk = NULL;
    }
    if (NULL != FactoryChair) {
        delete FactoryChair;
        FactoryChair = NULL;
    }
    return 0;
}
控制台输出结果
WoodDesk
WoodChair

上一篇下一篇

猜你喜欢

热点阅读