解释说明:
一个工厂可以生产同类型产品多件。方便创建 同种产品类型的 复杂参数 对象
工厂方法模式的意义是定义一个创建产品对象的工厂接口,将实际创建工作推迟到子类当中。核心工厂类不再负责产品的创建,这样核心类成为一个抽象工厂角色,仅负责具体工厂子类必须实现的接口,这样进一步抽象化的好处是使得工厂方法模式可以使系统在不修改具体工厂角色的情况下引进新的产品。
缺点
扩展性差(我想增加一具体产品需要修改工厂和增加一类产品类)
不同产品需要额外参数
改进:
多方法的工厂模式为不同产品,提供不同的生产方法,使用时 需要哪种产品就调用该种产品的方法,使用方便、容错率高。可以对不同产品设置不同参数。
#include <iostream>
using namespace std;
class IHuman
{
public:
IHuman(){}
virtual ~IHuman(){}
virtual void Laugh() = 0;
virtual void Cry() = 0;
virtual void Talk() = 0;
};
class CYellowHuman :public IHuman
{
public:
CYellowHuman(){}
~CYellowHuman(){}
void Laugh()
{
cout << "黄色人种会大笑,幸福呀!" << endl;
}
void Cry()
{
cout << "黄色人种会哭" << endl;
}
void Talk()
{
cout << "黄色人种会说话,一般说的都是双字节" << endl;
}
};
class CWhiteMan:public IHuman
{
public:
CWhiteMan(){}
~CWhiteMan(){}
void Laugh()
{
cout << "白色人种会笑" << endl;
}
void Cry()
{
cout << "白色人种会哭" << endl;
}
void Talk()
{
cout << "白色人种会说话,一般都是单字节" << endl;
}
};
class CBlackMan :public IHuman
{
public:
CBlackMan(){}
~CBlackMan(){}
void Laugh()
{
cout << "黑种人会笑" << endl;
}
void Cry()
{
cout << "黑种人会哭" << endl;
}
void Talk()
{
cout << "黑人可以说话,一般人听不懂" << endl;
}
};
class CSimple
{
public:
CSimple(){}
virtual ~CSimple(){}
virtual IHuman* CreateHuman(string classType);
};
IHuman* CSimple::CreateHuman(string classType)
{
if (classType.compare("CYellowHuman"))
return new CYellowHuman();
else if (classType.compare("CWhiteHuman"))
return new CWhiteMan();
else if (classType.compare("CBlackHuman"))
return new CBlackMan();
return NULL;
}
template<class T>
class CStand
{
public:
CStand(){}
~CStand(){}
T* CreateHuman()
{
return new T();
}
};
void dosimplefactory()
{
CSimple* p = new CSimple();
cout << "----------第一批人是这样的:黄种人" << endl;
IHuman* pYellowMan = p->CreateHuman("CYellowHuman");
((CYellowHuman*)pYellowMan)->Cry();
pYellowMan->Laugh();
pYellowMan->Talk();
delete pYellowMan;
cout << "----------第二批人是这样的:白种人" << endl;
IHuman* pWhiteMan = p->CreateHuman("CWhiteHuMan");
pWhiteMan->Cry();
pWhiteMan->Laugh();
pWhiteMan->Talk();
cout << "----------第三批人是这样的:黑种人" << endl;
CStand<CBlackMan> stand;
IHuman* pBlack = stand.CreateHuman();
pBlack->Cry();
pBlack->Laugh();
pBlack->Talk();
}
int main()
{
dosimplefactory();
return 0;
}