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

设计模式 -- 策略模式 + 简单工程模式(C++)

2012-07-27 11:22 295 查看
策略模式和简单工厂模式图,(基本一样)




类型:行为模式

定义一组算法,将每个算法都封装起来,并且使它们之间可以互换。策略模式使这些算法在客户端调用它们的时候能够互不影响地变化。
策略模式和简单工厂模式区别就是:简单工厂模式是实现对象的多样性,而策略模式适合类中的成员以方法为主;简单工厂模式只能解决对象创建问题,对于经常变动的算法应使用策略模式。
class basicObject
{
public:
virtual double GetResult()
{
double dResult=0;
return dResult;
}
protected:
int tempa;
int tempb;
};

class oneOperation : public basicObject
{
public:
oneOperation(int a,int b)
{
tempa=a;
tempb=b;
}
virtual double GetResult()
{
return (tempa * tempb) / 10;
}
};

class twoOperation : public basicObject
{
public:
twoOperation(int a,int b)
{
tempa=a;
tempb=b;
}
virtual double GetResult()
{
return (tempa * tempb - 300);
}
};

class Context
{
private:
basicObject* obj;
public:
Context(int cType, int valueT)
{
switch (cType)
{
case 1:
obj=new oneOperation(valueT, 8);
break;
case 2:

default:
obj=new twoOperation(valueT, 2);
break;
}
}
double GetResult()
{
return obj->GetResult();
}
};


#include "classFile.h"
#include "stdlib.h"
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
int a = 500, b = 1;
Context * test = new Context(b, a);
cout << "value = " << test->GetResult() << endl;
system("pause");
return 0;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: