码迷,mamicode.com
首页 > 其他好文 > 详细

简单工厂模式

时间:2015-04-14 12:51:00      阅读:126      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!