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

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

  • 相关阅读:
    三层架构之解耦
    自动升级 组件
    C语言常量与指针
    ASP.NET MVC Model元数据
    Web层后端权限模块
    java中文排序问题(转)
    JDWP
    bat执行java程序的脚本解析
    jdom dom4j解析xml不对dtd doctype进行验证(转)
    Dom4j SAXReader Constructors
  • 原文地址:https://www.cnblogs.com/hushpa/p/4424507.html
Copyright © 2011-2022 走看看