您的位置:首页 > 编程语言 > C语言/C++

C++设计模式从0进击-1-简单(静态)工厂模式

2017-01-18 13:01 441 查看
简单工厂模式的工厂类一般是使用静态方法,通过接收的参数的不同来返回不同的对象实例。

不修改代码的话,是无法扩展的。

 

[cpp] view
plain copy

 print?





#include <iostream>  

using namespace std;  

  

class COperation  

{  

public:  

    int m_nFirst;  

    int m_nSecond;  

  

    virtual double GetResult()  

    {  

        double dResult = 0;  

        return dResult;  

    }  

};  

  

//加法  

class AddOperation: public COperation  

{  

    virtual double GetResult()  

    {  

        return m_nFirst+ m_nSecond;  

    }  

};  

  

//减法  

class SubOperation: public COperation  

{  

public:  

    virtual double GetResult()  

    {  

        return m_nFirst - m_nSecond;  

    }  

};  

[cpp] view
plain copy

 print?





//工厂类  

[cpp] view
plain copy

 print?





class CCaculatorFactory  

{  

public:  

    static COperation * Create(char cOperator);  

};  

  

COperation * CCaculatorFactory::Create(char cOperator)  

{  

    COperation * oper;  

    switch(cOperator)  

    {  

    case '+':  

        oper = new AddOperation();  

        break;  

    case '-':  

        oper = new SubOperation();  

        break;  

    default:  

        oper = new AddOperation();  

        break;  

    }  

    return oper;  

}  

[cpp] view
plain copy

 print?





int _tmain(int argc, _TCHAR * argv [])  

{  

         int a, b;  

         cin >> a >> b;  

         COperation * op = CCaculatorFactory::Create('-');  

         op->m_nFirst = a;  

         op->m_nSecond = b;  

         cout << op->GetResult() << endl;  

         return 0;  

}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: