简单工厂模式 - C++的《大话设计模式》

该代码示例展示了如何在C++中利用继承和多态性来处理四则运算。定义了一个基类`Operation`,然后创建了四个派生类(加法、减法、乘法、除法),每个类覆盖了`getResult`方法以执行相应的运算。此外,还有一个`OperationFactory`类作为工厂,根据输入的运算符创建相应的运算对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <math.h>
#include <string>
#include <memory>
/*
 * 以四则运算为例,应用C++的继承多态特性
 * 通过运算基类管理操作数,派生运算类以实现并分离各运算逻辑
 * 再通过独立的工厂类实例化运算类对象
 */
class Operation
{
public:
	Operation(int A = 0, int B = 0) : m_operandA(A), m_operandB(B) {}
	~Operation() = default;
	void setOperandA(double num)
	{
		m_operandA = num;
	}
	void setOperandB(double num)
	{
		m_operandB = num;
	}
	virtual double getResult()
	{
		double result = 0.0;
		return result;
	}

protected:
	int m_operandA;
	int m_operandB;
};

class OperationAdd
	: public Operation
{
public:
	double getResult() override
	{
		double result = 0.0;
		result = m_operandA + m_operandB;
		return result;
	}
};

class OperationSub : public Operation
{
public:
	double getResult() override
	{
		double result = 0.0;
		result = m_operandA - m_operandB;
		return result;
	}
};

class OperationMultiply : public Operation
{
public:
	double getResult() override
	{
		double result = 0.0;
		result = m_operandA * m_operandB;
		return result;
	}
};

class OperationDiv : public Operation
{
public:
	double getResult() override
	{
		if (0 == m_operandB)
		{
			std::cout << "error: num divided by ZERO" << std::endl;
			exit(1);
		}
		double result = 0.0;
		result = m_operandA / m_operandB;
		return result;
	}
};

class OperationOrder
	: public Operation
{
public:
	double getResult() override
	{
		double result = 0;
		result = pow(m_operandA, m_operandB);
		return result;
	}
};

class OperationFactory
{
public:
	std::shared_ptr<Operation> createOperation(std::string operate)
	{
		if (operate == "+")
		{
			m_oper = std::make_shared<OperationAdd>();
		}
		if (operate == "-")
		{
			m_oper = std::make_shared<OperationSub>();
		}
		if (operate == "*")
		{
			m_oper = std::make_shared<OperationMultiply>();
		}
		if (operate == "/")
		{
			m_oper = std::make_shared<OperationDiv>();
		}

		return m_oper;
	}

private:
	std::shared_ptr<Operation> m_oper;
};

int main()
{
	OperationFactory factory;
	std::shared_ptr<Operation> oper = factory.createOperation("+");
	std::cout << oper.use_count() << std::endl;
	oper->setOperandA(1);
	oper->setOperandB(2);
	std::cout << "add(1,2): " << oper->getResult() << std::endl;

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值