[大话设计模式] 第1章: 简单工厂模式
适用场景
-
需要创建的对象很多,通常包含switch case或者if else语句,此时将对象的创建移入工厂类中
-
由于对象的创建过程是我们不需要去关心的,而我们注重的是对象的实际操作,所以,我们需要分离对象的创建和操作两部分,如此,方便后期的程序扩展和维护。
UML类图
ProductA、ProductB和ProductC继承自Product虚拟类,Show方法是不同产品的自描述;Factory依赖于ProductA、ProductB和ProductC,Factory根据不同的条件创建不同的Product对象。
C++实现
#include <iostream>
using namespace std;
typedef enum
{
TypeA = 0,
TypeB,
TypeC,
} PRODUCTTYPE;
class Product
{
public:
virtual ~Product(){}
virtual void show() = 0;
};
class ProductA : public Product
{
public:
void show(){
cout << "ProductA" << endl;
}
};
class ProductB : public Product
{
public:
void show(){
cout << "ProductB" << endl;
}
};
class ProductC : public Product
{
public:
void show(){
cout << "ProductC" << endl;
}
};
class Factory
{
public:
Product *create_product(PRODUCTTYPE type);
};
Product *Factory::create_product(PRODUCTTYPE type)
{
Product *pro;
switch(type)
{
case TypeA:
pro = new ProductA(); break;
case TypeB:
pro = new ProductB(); break;
case TypeC:
pro = new ProductC(); break;
default:
pro == NULL;
}
return pro;
}
int main()
{
Factory *proFactory = new Factory();
Product *proA = proFactory->create_product(TypeA);
if(proA)
proA->show();
Product *proB = proFactory->create_product(TypeB);
if(proB)
proB->show();
Product *proC = proFactory->create_product(TypeC);
if(proC)
proC->show();
delete proA;
delete proB;
delete proC;
delete proFactory;
return 0;
}
http://www.cnblogs.com/moon1992/