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 阅读(1156) 评论(0) 编辑 收藏 举报