主要特点是需要在工厂类中做判断,从而创造相应的产品,当增加新产品时,需要修改工厂类。使用简单工厂模式,我们只需要知道具体的产品型号就可以创建一个产品。
缺点:工厂类集中了所有产品类的创建逻辑,如果产品量较大,会使得工厂类变的非常臃肿。
#include <string>
using std::string;
class Tank
{
public:
virtual const string& type() = 0;
virtual ~Tank(){};
};
class Tank56:public Tank
{
public:
Tank56()
: m_strType("Tank56")
{
p = new char[20];
printf("class Tank56 constructor!\n");
}
~Tank56()
{
delete[] p;
p = NULL;
printf("class Tank56 destructor!\n");
}
const string& type()
{
return m_strType;
}
private:
string m_strType;
char* p;
};
class Tank92:public Tank
{
public:
Tank92()
: m_strType("Tank92")
{
p = new char[20];
printf("class Tank92 constructor!\n");
}
~Tank92()
{
delete[] p;
p = NULL;
printf("class Tank92 destructor!\n");
}
const string& type()
{
return m_strType;
}
private:
string m_strType;
char* p;
};
class Factory
{
public:
virtual Tank* createTank(string strType) = 0;
};
class TankFactory: public Factory
{
public:
Tank* createTank(string strType)
{
if(strType == "Tank56")
return new Tank56();
else if(strType == "Tank92")
return new Tank92();
}
};
int main(int argc, _TCHAR* argv[])
{
TankFactory tf;
Tank* a = tf.createTank("Tank56");
delete a;
return 0;
}
参考:https://www.cnblogs.com/chengjundu/p/8473564.html
https://www.cnblogs.com/xuaidongstdudyrecording/p/6016036.html