• 工厂方法模式


    #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;
    } */
    
    /* FactoryMethod 类 */
    class IFactory {
    public:
        virtual Operation* createOperation() = 0;
    };
    
    class AddFactory: public IFactory {
    public:
        Operation* createOperation() {return new OperationAdd();}
    };
    
    class SubFactory: public IFactory {
    public:
        Operation* createOperation() {return new OperationSub();}
    };
    
    /* 测试 */
    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; */
    
        /* 工厂方法 */
        IFactory *factory = new AddFactory(); //若要使用OperationSub,则直接在此处改为SubFactory工厂类即可
        Operation *oper = factory->createOperation();
        oper->setOperands(32, 23);
        cout<<"Result: "<<oper->getRlt()<<endl;
        delete oper;
        delete factory;
    
        system("pause");
    }

    Tips:

    工厂方法模式是对简单工厂模式的进一步抽象和推广,在简单工厂模式中,若要增加新的操作类,那么就必须修改SimpleFactory 类。

    工厂方法类则只需要增加一个新的子工厂类即可,遵循开闭原则。 但是在使用中,选择哪个工厂类的判断逻辑留在了客户端中。

  • 相关阅读:
    《2048》开发5——实现计分功能
    《2048》开发4——继续编辑GameView类,实现游戏逻辑
    《2048》开发3——编辑Card类
    robotframework(rf)中对时间操作的datetime库常用关键字
    弹框和单选框,复选框
    Selenium IDE安装与使用
    全面的功能测试点总结
    RF新手常见问题总结--(基础篇)
    常用断言关键字(rf中)
    jmeter录制(ios)app脚本
  • 原文地址:https://www.cnblogs.com/hushpa/p/4431919.html
Copyright © 2020-2023  润新知