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;
    } */
    
    /* 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 类。

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

  • 相关阅读:
    认识Linux
    Java之安装环境
    Markdown学习
    使用cacti监控linux server的接口流量
    IDRAC安装dell服务器操作系统(linux or windows),用到生命周期管理器
    网络编程--练习题
    linux搭建ntp服务器-添加交换机客户端,windows客户端
    linux centos7搭建redis-5.0.5
    linux centos7搭建mysql-5.7.29
    对称加密与非对称加密
  • 原文地址:https://www.cnblogs.com/hushpa/p/4431919.html
Copyright © 2011-2022 走看看