一、大话设计模式之简单工厂模式

一、简单工厂模式:用一个工厂来根据输入的条件产生不同的类,通过根据不同类的virtual函数得到不同的结果,运用c++多态的特性。用于创建对象,在新添加类时,不会影响以前的系统代码。


GOOD:适用于不同情况创建不同的类时
BUG:客户端必须要知道基类和工厂类,耦合性差
(工厂类与基类为关联关系)

代码如下:


class COperation
{
public:
	int m_nFirst;
	int m_nSecond;
	virtual double GetResult()
	{
		double dResult = 0;
		return dResult;
	}
};
//加法
class AddOperation: public COperation
{
public:
		virtual double GetResult()
	{
		return m_nFirst + m_nSecond;
	}
};


//减法
class SubOperation : public COperation
{
public:
	virtual double GetResult()
	{
		return m_nFirst - m_nSecond;
	}
};
//工厂类
class CCalculatorFactory
{
public:
	static  COperation* Create(char cOperator);
};
COperation* CCalculatorFactory::Create(char cOperator)
{
	COperation *oper;
	switch (cOperator)
	{
		case '+':
			oper = new AddOperation();
			break;
		case '-':
			oper = new SubOperation();
			break;
		default:
			oper = new AddOperation();
			break;
	}
	return oper;
};




int main()
{

	int a, b;
	cin >> a >> b;
	COperation * op = CCalculatorFactory::Create('-');
	op->m_nFirst = a;
	op->m_nSecond = b;
	cout << op->GetResult() << endl;
	system("pause");
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值