标签:
简单工厂模式就是一个工厂根据不同的产品类型可以生产出不同的产品,如下所示Factory 根据不同类型(A、B)产生不同的产品(ProductA,ProcuctB)
#include <iostream> using namespace std; enum ProductType { A = 1, B = 2 }; class Product { public: virtual ~Product(){} virtual void create() = 0; }; class ProductA : public Product { void create(){ cout << "A create()" << endl;} }; class ProductB : public Product { void create(){ cout << "B create()" << endl;} }; class Factory { public: Product* createProduct(ProductType type) { switch(type) { case A: return new ProductA(); case B: return new ProductB(); } return nullptr; } }; int main() { Factory* f = new Factory(); Product* pa = f->createProduct(A); Product* pb = f->createProduct(B); pa->create(); pb->create(); delete pa; pa = nullptr; delete pb; pb = nullptr; delete f; f = nullptr; }
标签:
原文地址:http://www.cnblogs.com/laogaoyang/p/5852357.html