工厂方法模式

#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 类。

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

原文地址:https://www.cnblogs.com/hushpa/p/4431919.html