策略模式

作者在 2014-03-11 23:07:29 发布以下内容

    定义算法家族,分别封装起来,让它们之间可以相互替换,让算法变化,不会影响到用户。

    GOOD:适合类中的成员以方法为主,算法经常变动;简化了单元测试(因为每个算法都有自己的类,可以通过自己的接口单独测试)。

    策略模式和简单工厂基本相同,但简单工厂模式只能解决对象创建问题,对于经常变动的算法应使用策略模式。

    BUG:客户端要做出判断

//策略基类
class COperation
{
public:
int m_nFirst;
int m_nSecond;
virtual double GetResult()
{
return 0;
}
};

//策略具体类——加法类
class AddOperation : public COperation
{
public:
AddOperation(int a, int b)
{
m_nFirst = a;
m_nSecond = b;
}
double GetResult()
{
return m_nFirst + m_nSecond;
}
};
//策略具体类——减法类
class SubOperation : public COperation
{
public:
SubOperation(int a, int b)
{
m_nFirst = a;
m_nFirst = b;
}
double GetResult()
{
return m_nFirst - m_nSecond;
}
};
class Context
{
private:
COperation *op;
public:
Context(COperation *temp)
{
op = temp;
}
~Context()
{
delete op;
}
double GetResult()
{
return op->GetResult();
}
};

int main()
{
int a, b;
char c;
cout << "请输入两个操作数:";
cin >> a >> b;
cout << "请输入运算符:";
cin >> c;
Context *pContext = NULL;
switch(c)
{
case '+':
pContext = new Context(new AddOperation(a, b));
cout << pContext->GetResult() << endl;
break;
case '-':
pContext = new Context(new SubOperation(a, b));
cout << pContext->GetResult() << endl;
break;
default:
break;
}
if(pContext != NULL)
delete pContext;
return 0;
}

大话设计模式 | 阅读 1220 次
文章评论,共0条
游客请输入验证码