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

策略模式和简单工厂模式图,(基本一样)


 类型:行为模式

    定义一组算法,将每个算法都封装起来,并且使它们之间可以互换。策略模式使这些算法在客户端调用它们的时候能够互不影响地变化。

 策略模式和简单工厂模式 区别就是: 简单工厂模式是实现对象的多样性,而策略模式适合类中的成员以方法为主;简单工厂模式只能解决对象创建问题,对于经常变动的算法应使用策略模式。

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;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值