1、策略模式和简单工厂基本相同,但简单工厂模式只能解决对象创建问题,对于经常变动的算法应使用策略模式。
2、例子
//基类
class COperation
{
public:
int m_nFirst;
int m_nSecond;
virtual double GetResult()
{
double dResult = 0;
return dResult;
}
};
//策略具体类--加法
class AddOperation : public COperation
{
public:
AddOperation(int a, int b)
{
m_nFirst = a;
m_nSecond = b;
}
virtual double GetResult()
{
return m_nFirst + m_nSecond;
}
};
//减法
class SubOperation : public COperation
{
public:
SubOperation(int a, int b)
{
m_nFirst = a;
m_nSecond = b;
}
virtual double GetResult()
{
return m_nFirst - m_nSecond;
}
};
//工厂类
class Context
{
private:
COperation* op;
public:
Context(COperation* temp)
{
op = temp;
}
double GetResult()
{
return op->GetResult();
}
}
//客户端
int main()
{
int a, b;
char c;
cin >> a >> b;
cout << "请输入运算符:";
cin >> c;
switch(c)
{
case '+':
Context* context = new Context(new AddOperation(a, b));
cout << context->GetResult() << endl;
break;
case '-':
Context* context = new Context(new SubOperation(a, b));
cout << context->GetResult() << endl;
break;
default:
break;
}
}