zoukankan      html  css  js  c++  java
  • 简单工厂模式

    #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. 更抽象,对用户隐藏了各个派生类。

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

  • 相关阅读:
    Python数据类型之数值-Python基础前传(5)
    R语言之数据可视化
    R语言之数据可视化
    R语言基础
    R语言基础
    R语言基础
    R语言入门
    R语言入门
    用 python 爬取 gutenberg 上的英文科幻小说
    Python 在数据科学中的应用
  • 原文地址:https://www.cnblogs.com/hushpa/p/4424507.html
Copyright © 2011-2022 走看看