首页 > 其他 > 详细

简单工厂模式

时间:2015-04-14 12:50:53      阅读:170      评论:0      收藏:0      [点我收藏+]
#include <iostream>

using namespace std;

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;}
};

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");
}

 

简单工厂模式

原文:http://www.cnblogs.com/hushpa/p/4424507.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!