简单工厂模式

使用SimpleFactory模式简化操作类的使用
本文介绍了一种使用SimpleFactory模式简化操作类(如加法、减法等)在程序中的调用方式,使得逻辑更加清晰,对用户隐藏了各个派生类的实现细节,便于维护。
#include <iostream>

using namespace std;

/* Operation 基类和子类 */
class Operation {

public:
    void setOperands(const int operA = 0, const int operB = 0) {m_operandA = operA; m_operandB = operB;}
    virtual int getRlt() = 0;

protected:
    int m_operandA;
    int m_operandB;
};

class OperationAdd : public Operation {
public:
    int getRlt() {return m_operandA + m_operandB;}
};

class OperationSub : public Operation {
public:
    int getRlt() {return m_operandA - m_operandB;}
};

/* SimpleFactory 类 */
class SimpleFactory {
public:
    static Operation* createOperation(char oper);
};

Operation* SimpleFactory::createOperation(char oper) {
    Operation *operation = NULL;
    switch (oper) {
    case '+':
        operation = new OperationAdd();
        break;
    case '-':
        operation = new OperationSub();
        break;
    }
    return operation;
}

/* 测试 */
void main() {
    Operation *oper = NULL;
    oper = SimpleFactory::createOperation('+');
    oper->setOperands(32, 23);
    cout<<"Result: "<<oper->getRlt()<<endl;
    delete oper;

    oper = SimpleFactory::createOperation('-');
    oper->setOperands(32, 23);
    cout<<"Result: "<<oper->getRlt()<<endl;
    delete oper;

    system("pause");
}

 

基本思想:

为什么使用simple factory模式?

当基类的派生类很多时,比如OperationAdd,OperationSub, OperationMulti etc. 使用它们时需要通过各个名字来创建,

如果使用simple facotry类来管理,对用户而言

1. 逻辑就更清晰

2. 更抽象,对用户隐藏了各个派生类。

对开发者而言,逻辑同样更清晰了,易于维护。

转载于:https://www.cnblogs.com/hushpa/p/4424507.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值