2.由于对象的创建过程是我们不需要去关心的,而我们注重的是对象的实际操作,所以,我们需要分离对象的创建和操作两部分,如此,方便后期的程序扩展和维护。
代码实现:
/*
** FileName : SimpleFactoryPatternDemo
** Author : Jelly Young
** Date : 2013/11/17
** Description : More information
*/
#include <iostream>
#include <vector>
using namespace std;
typedef enum ProductTypeTag
{
TypeA,
TypeB,
TypeC
}PRODUCTTYPE;
// Here is the product class
class Product
{
public:
virtual void Show() = 0;
};
class ProductA : public Product
{
public:
void Show()
{
cout<<"I'm ProductA"<<endl;
}
};
class ProductB : public Product
{
public:
void Show()
{
cout<<"I'm ProductB"<<endl;
}
};
class ProductC : public Product
{
public:
void Show()
{
cout<<"I'm ProductC"<<endl;
}
};
// Here is the Factory class
class Factory
{
public:
Product* CreateProduct(PRODUCTTYPE type)
{
switch (type)
{
case TypeA:
return new ProductA();
case TypeB:
return new ProductB();
case TypeC:
return new ProductC();
default:
return NULL;
}
}
};
int main(int argc, char *argv[])
{
// First, create a factory object
Factory *ProductFactory = new Factory();
Product *productObjA = ProductFactory->CreateProduct(TypeA);
if (productObjA != NULL)
productObjA->Show();
Product *productObjB = ProductFactory->CreateProduct(TypeB);
if (productObjB != NULL)
productObjB->Show();
Product *productObjC = ProductFactory->CreateProduct(TypeC);
if (productObjC != NULL)
productObjC->Show();










