c++设计模式之工厂模式

工厂模式更像是将简单工厂模式在开闭原则的情况(对修改关闭对新加开放)进行了修改。

#include <iostream>
#include <string>
using namespace std;


/*	工厂模式
*	工厂模式就是定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使
*	一个类的实例化延迟到子类。
*	工厂模式和简单工厂模式的区别,简单工厂模式是通过客户端传入type,在简单工厂类中动态
*	生成该对象。而工厂模式是通过客户端自己生成一个对象。
*/

class CLeiFeng
{
public:
	CLeiFeng() {}
	virtual ~CLeiFeng() {}
	void Wash() { cout << "洗衣服" << endl; }
	virtual void DoSpecial() = 0;
};

class CUndergradute : public CLeiFeng
{
public:
	CUndergradute() {}
	virtual void DoSpecial() { cout << "读书" << endl; }
};
class CVolunteer : public CLeiFeng
{
public:
	CVolunteer() {}
	virtual void DoSpecial() { cout << "拖地" << endl; }
};
class IFactory
{
public:
	IFactory() {}
	virtual CLeiFeng* CreateLeiFeng() = 0;
};

class CUndergraduteFactory : public IFactory
{
public:
	CUndergraduteFactory() {}
	virtual CLeiFeng* CreateLeiFeng() {
		return new (std::nothrow) CUndergradute();
	}
};

class CVolunteerFactory : public IFactory
{
public:
	CVolunteerFactory() {}
	virtual CLeiFeng* CreateLeiFeng()
	{
		return new (std::nothrow) CVolunteer();
	}
};
int main()
{
	IFactory* pfactory = new CVolunteerFactory();
	if (nullptr == pfactory)
	{
		cout << "" << endl;
		return -1;
	}
	CLeiFeng* pLeiFeng = pfactory->CreateLeiFeng();
	pLeiFeng->DoSpecial();
	delete pLeiFeng;
	delete pfactory;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值