策略模式
目标:定义算法家族,分别把不同的算法封装起来,让它们之间可以相互替换,算法的变化不会影响到用户。
优点:适合类中的成员以方法为主,算法经常变动的情况。简化了单元测试,因为每个算法都有自己的类,可以通过自己的接口单独测试。
策略模式和简单工厂基本相同,但简单工厂模式只能解决对象创建问题,对于经常变动的算法应使用策略模式。
缺点:客户端要做出判断
下面是代码:
#include
//策略基类
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 MulOperation : public COperation
{
public:
MulOperation(int a,int b)
{
m_nFirst = a;
m_nSecond = b;
}
virtual double GetResult()
{
return m_nFirst * m_nSecond;
}
};
//策略具体类——除法类
class DivOperation : public COperation
{
public:
DivOperation(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;
std::cin >> a >> b;
std::cout << "请输入运算符: ";
std::cin >> c;
switch(c)
{
case '+':
{
Context* context = new Context(new AddOperation(a,b));
std::cout << context->GetResult() << std::endl;
}
break;
case '-':
{
Context* context = new Context(new SubOperation(a,b));
std::cout << context->GetResult() << std::endl;
}
break;
case '*':
{
Context* context = new Context(new MulOperation(a,b));
std::cout << context->GetResult() << std::endl;
}
break;
case '/':
{
Context* context = new Context(new DivOperation(a,b));
std::cout << context->GetResult() << std::endl;
}
break;
default:
std::cout << "no so operation" << std::endl;
break;
}
return 0;
}
阅读(618) | 评论(0) | 转发(0) |