#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;
}
简单工厂模式 - C++的《大话设计模式》
于 2023-01-15 23:13:11 首次发布