首先非常感谢睡仔:工厂模式,我的所有工厂模式的理解均来自于他的博客思想。
factory.h
//设计模式之工厂方法,此方式是在product基础上对factory进一步抽象的结果
/*
优点:
1、解决了大量new的问题,
2、通过在类的内部创建对象,通常比直接创建对象更加灵活
3、当系统增加产品时,新增一个产品工厂即可,对抽象工厂不受影响
缺点:
对创建不同系列的产品无能为力(需要改动抽象的factory)
适用性:
1、当一个类不知道它所必须创建的对象的类的时候
2、当一个类希望由它的子类来指点它所创建的对象的时候
3、当类将创建对象的职责委托给多个帮助子类中的某一个,并且你希望将哪一个帮助子类是代理者这一信息局部化的时候。
*/
//定义产品类的基类
class product//cookfood
{
protected://控制不让用户直接实例化
product();
public:
virtual ~product();
virtual void cooking() = 0;//做菜的接口
};
//一下每个实例化,相当于生成一个类型的产品
//实例化具体实例A,可以理解成做红烧鱼
class concreteproductA :public product
{
public:
concreteproductA();
virtual ~concreteproductA();
virtual void cooking();//做菜
};
//实例化具体实例B,可以理解成做回锅肉
class concreteproductB :public product
{
public:
concreteproductB();
virtual ~concreteproductB();
virtual void cooking();//做菜
};
//将factory提取出来
class factory
{
public:
factory();
virtual ~factory();
public:
//
virtual product* createproduct(int producttype = 0) = 0;
};
//下面的factory均继承自factory
class concretefactory1:public factory
{
public:
concretefactory1();
virtual ~concretefactory1();
public:
product* createproduct(int producttype);
};
class concretefactory2:public factory
{
public:
concretefactory2();
virtual ~concretefactory2();
public:
product* createproduct(int producttype);
};
factory.cpp
#include "factory.h"
#include <stdio.h>
product::product()
{
}
product::~product()
{
}
concreteproductA::concreteproductA()
{
}
concreteproductA::~concreteproductA()
{
}
void concreteproductA::cooking()
{
printf("concreteproductA cooking 红烧鱼\n");
}
concreteproductB::concreteproductB()
{
}
concreteproductB::~concreteproductB()
{
}
void concreteproductB::cooking()
{
printf("concreteproductB cooking 回锅肉\n");
}
factory::factory()
{
}
factory::~factory()
{
}
concretefactory1::concretefactory1()
{
}
concretefactory1::~concretefactory1()
{
}
product* concretefactory1::createproduct(int producttype)
{
product *p = NULL;
switch(producttype)
{
/*case 0:
p = new concreteproductA();
break;
case 1:
p = new concreteproductA();
break;*/
default:
p = new concreteproductA();
}
return p ;
}
concretefactory2::concretefactory2()
{
}
concretefactory2::~concretefactory2()
{
}
product* concretefactory2::createproduct(int producttype)
{
product *p = NULL;
switch(producttype)
{
/*case 0:
p = new concreteproductA();
break;
case 1:
p = new concreteproductB();
break;*/
default:
p = new concreteproductB();
}
return p ;
}
int main()
{
factory *fct = new concretefactory1();
product *p = fct->createproduct(1);
p->cooking();
delete p;
delete fct;
fct = new concretefactory2();
p = fct->createproduct(2);
p->cooking();
delete p;
delete fct;
}
重点理解factory.h中各类之间的关系。
另外,这篇博客介绍的非常好,仅供参考:http://blog.csdn.net/wuzhekai1985/article/details/6660462