设计模式C++版:第零式简单工厂

在前面介绍C++基础的时候,我们写了一个简单地计算类 http://blog.csdn.net/thedarkfairytale/article/details/51750971 。考虑到易扩展和复用的特性,下面使用设计模式的简单工厂类实现一下(自己对着代码动手敲一下,感觉绝对不同)

class Operation
{
public:
	virtual double getresult(){ return 0; }
public:
	double m_firstnum;
	double m_secondnum;
};

class OperationAdd :public Operation
{
public:
	double getresult(){ return m_firstnum + m_secondnum; }
};

class OperationSub :public Operation
{

public:
	double getresult(){ return m_firstnum - m_secondnum; }
};

class OperationMul :public Operation
{

public:
	double  getresult(){ return m_firstnum * m_secondnum; }
};

class OperationDiv :public Operation
{
public:
	double getresult()
	{
		if (0 != m_secondnum)
		{
			return m_firstnum / m_secondnum;
		}
		else
		{
			printf("the second number can't be zero!");
			return 0;
		}
	}
};
enum class ENUMOPERATION   //枚举类 避免隐式转换的污染
{
	ADD = 1,
	SUB = 2,
	MUL = 3,
	DIV = 4
};

class SimpleFactory
{
public:
	SimpleFactory():m_oper(nullptr){}
	Operation &createoperaton(ENUMOPERATION oper);

private:
	Operation * m_oper;
};

Operation& SimpleFactory::createoperaton(ENUMOPERATION oper)
{
	if (m_oper!=nullptr)
	{
		delete m_oper;
		m_oper = nullptr;
	}
	
	switch (oper)
	{

	case ENUMOPERATION::ADD:
		m_oper = new OperationAdd;
		break;
	case ENUMOPERATION::SUB:
		m_oper = new OperationSub;
		break;
	case ENUMOPERATION::MUL:
		m_oper = new OperationMul;
		break;
	case ENUMOPERATION::DIV:
		m_oper = new OperationDiv;
		break;
	default:
		m_oper = new OperationAdd;
		break;
	}
	return *m_oper;
}
int main()
{
	Operation *oper;     
	SimpleFactory factory;
	oper = &factory.createoperaton(ENUMOPERATION::ADD);
	oper->m_firstnum = 12;
	oper->m_secondnum = 21;
	cout << oper->getresult() <<endl;
	return 0;
}



使用简单工厂模式后的代码,和之前简单的封装以后对比发现,之前的单一接口,都变成了一个运算类,这样的好处是,我们隔离了各种运算,想要复用其中的一个算法不用把其他的也都牵连进来。

如果我们修改加法,则不必和减法产生任何关联,同理修改乘法也不必和除法有什么关联,另外我们添加其他运算方式也方便同时不至于一个类变得太大。如果我们只想使用复用加法和减法,那么我们只需把加减法的运算类拿过来使用即可,不必和乘除法有什么联系。但简单工厂也是很多不足,比如每次添加或减少运算类,都要修改工厂类,在一定程度上降低了工厂类的封装性。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值