设计模式 之 《策略模式》

 

 

#ifndef __STRATEGY_MODEL__
#define __STRATEGY_MODEL__

//策略基类
class Operation
{
public:
    double m_nFirst;
    double m_nSecond;

    virtual double getResult()
    {
        double dResult = 0;
        return dResult;
    }
};

//策略具体类 加法类
class AddOperation : public Operation
{
public:
    AddOperation(int a, int b)
    {
        m_nFirst = a;
        m_nSecond = b;
    }
    double getResult()
    {
        return m_nFirst+m_nSecond;
    }
};

class Context
{
private:
    Operation* op;

public:
    Context(char cType, int a, int b)
    {
        switch (cType)
        {
        case '+':
                op = new AddOperation(a,b);
            break;
        default:
            break;
        }
    }
    double getResult()
    {
        return op->getResult();
    }
};

#endif //__STRATEGY_MODEL__


GOOD:客户端只需访问Context类,而不用知道其他任何类信息,实现了低耦合。
int _tmain(int argc, _TCHAR* argv[])
{
    int a,b;
    char c;
    cin>>a>>c>>b;
    Context* context = new Context(c,a,b);
    cout<<context->getResult()<<endl;

    return 0;
}

 

posted @ 2013-10-21 22:17  解放1949  阅读(151)  评论(0编辑  收藏  举报