c++设计模式之简单工厂模式(无内存泄漏)

主要特点是需要在工厂类中做判断,从而创造相应的产品,当增加新产品时,需要修改工厂类。使用简单工厂模式,我们只需要知道具体的产品型号就可以创建一个产品。

缺点:工厂类集中了所有产品类的创建逻辑,如果产品量较大,会使得工厂类变的非常臃肿。

#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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值