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 2016-03-23 17:08 caiminfeng 阅读(1154) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· 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