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

#include <iostream>
#include <math.h>
#include <string>
#include <memory>

/*
 * 简单工厂模式中,在工厂类内通过case实例化运算类对象,这样新的逻辑需要修改工厂类,
 * 违背了开发封闭原则。
 *
 * “工厂方法模式定义创建对象的接口,让字类决定实例化哪个运算类”
 * 根据依赖倒转原则,工厂类抽象接口,接口仅一个方法用于创建抽象产品,再让具体类的工厂实现接口。
 *
 *
 * 抽象产品类为基类,解耦合
 * 派生具体产品类
 * 抽象接口类负责实例化业务逻辑对象 -> 抽象产品类= IFactory::Produce();
 * 从接口类派生具体工厂类负责直接实例化产品 IFactory if = new ProductAFactory();
 */
class Operation
{
public:
	Operation(int A = 0, int B = 0) : m_operandA(A), m_operandB(B) {}

	void setOperandA(double num)
	{
		m_operandA = num;
	}

	void setOperandB(double num)
	{
		m_operandB = num;
	}
	virtual double getResult() = 0;

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 FactoryInterface
{
public:
	virtual std::shared_ptr<Operation> CreateFactory() = 0;
	virtual ~FactoryInterface() = default;
};

class FactoryAdd : public FactoryInterface
{
public:
	virtual std::shared_ptr<Operation> CreateFactory()
	{
		return std::make_shared<OperationAdd>();
	}
};

class FactorySub : public FactoryInterface
{
public:
	virtual std::shared_ptr<Operation> CreateFactory()
	{
		return std::make_shared<OperationSub>();
	}
};

class FactoryMultiply : public FactoryInterface
{
public:
	virtual std::shared_ptr<Operation> CreateFactory()
	{
		return std::make_shared<OperationMultiply>();
	}
};

class FactoryDiv : public FactoryInterface
{
public:
	virtual std::shared_ptr<Operation> CreateFactory()
	{
		return std::make_shared<OperationDiv>();
	}
};

int main()
{
	std::unique_ptr<FactoryInterface> operationFactory = std::make_unique<FactoryAdd>();
	std::shared_ptr<Operation> oper = operationFactory->CreateFactory();
	std::cout << oper.use_count() << std::endl;

	oper->setOperandA(1);
	oper->setOperandB(2);
	std::cout << "add(1,2): " << oper->getResult() << std::endl;
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值