C++简单工厂模式

简单工厂模式可以说是大多数人接触到的第一个设计模式。资源请求者(客户)直接调用工厂类中的函数,工厂根据传入的参数返回不同的类给资源请求者。下面给出在C++中使用简单工厂模式的一个demo,采用了auto_ptr智能指针管理类资源。

值得注意的是抽象类Product中的析构函数必须为虚函数。《Effective C++》条款07:为多态基类声明virtual析构函数。

采用auto_ptr也符合《Effective C++》条款13:以对象管理资源、条款18:让接口容易被正确使用,不易被误用。

复制代码
#include <iostream>
using namespace std;

enum ProductType{ TypeA, TypeB, TypeC };

class Product{
public:
    virtual void show() = 0;
    virtual ~Product(){};//virtual destructor
};

class ProductA :public Product{
public:
    void show(){
        cout << "A" << endl;
    }
    ProductA(){
        cout << "constructing A" << endl;
    }
    ~ProductA(){
        cout << "destructing A" << endl;
    }
};

class ProductB :public Product{
public:
    void show(){
        cout << "B" << endl;
    }
    ProductB(){
        cout << "constructing B" << endl;
    }
    ~ProductB(){
        cout << "destructing B" << endl;
    }
};

class ProductC :public Product{
public:
    void show(){
        cout << "C" << endl;
    }
    ProductC(){
        cout << "constructing C" << endl;
    }
    ~ProductC(){
        cout << "destructing C" << endl;
    }
};

class ProductFactory{
public:
    static auto_ptr<Product> createProduct(ProductType type){
        switch (type){
        case TypeA: return auto_ptr<Product>(new ProductA());
        case TypeB: return auto_ptr<Product>(new ProductB());
        case TypeC: return auto_ptr<Product>(new ProductC());
        default: return auto_ptr<Product>(NULL);
        }
    }
};


int main()
{
    {
        auto_ptr<Product> proA = ProductFactory::createProduct(TypeA);
        auto_ptr<Product> proB = ProductFactory::createProduct(TypeB);
        auto_ptr<Product> proC = ProductFactory::createProduct(TypeC);
        proA->show();
        proB->show();
        proC->show();
    }
    system("pause");
}
复制代码

 

posted on   caiminfeng  阅读(1154)  评论(0编辑  收藏  举报

编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示