策略模式(C++)

定义

定义一系列算法,把它们一个个封装起来,并且使它们可互相替换((变化)。该模式使得算法可独立手使用它的客户程序稳定)而变化(扩展,子类化)。
——《设计模式》GoF

使用场景

  • 在软件构建过程中,某些对象使用的算法可能多种多样,经常改变,如果将这些算法都编码到对象中,将会使对象变得异常复杂;而且有时候支持不使用的算法也是一个性能负担。
  • 如何在运行时根据需要透明地更改对象的算法?将算法与对象本身解耦,从而避免上述问题?

结构

在这里插入图片描述

代码示例

//Strategy.h
/****************************************************/
#ifndef STRATEGY_H
#define STRATEGY_H
#include<iostream>
using namespace std;
 
//创建一个定义活动的Strategy的抽象接口
class Strategy
{
public:
	Strategy() {};
	virtual ~Strategy() {};
	virtual int doOperation(int num1, int num2)=0;
};
 
//创建一个实体活动的OperationAdd类
class OperationAdd:Strategy
{
public:
	OperationAdd() {};
	virtual ~OperationAdd() {};
	int doOperation(int num1, int num2) { return num1 + num2; };
};
 
//创建一个实体活动的OperationSubstract类
class OperationSubstract :Strategy
{
public:
	OperationSubstract() {};
	virtual ~OperationSubstract() {};
	int doOperation(int num1, int num2) { return num1 - num2; };
};
 
//创建一个实体活动的OperationMultiply类
class OperationMultiply :Strategy
{
public:
	OperationMultiply() {};
	virtual ~OperationMultiply() {};
	int doOperation(int num1, int num2) { return num1 * num2; };
};
 
//创建一个使用某种策略的Context类
class Context
{
public:
	Context(Strategy *strate) { mstrate = strate; };
	virtual ~Context() { delete mstrate; mstrate = NULL; };
	int executeStrategy(int num1, int num2) { return mstrate->doOperation(num1,num2); };
private:
	Strategy *mstrate;
};

#endif


//test.cpp
/****************************************************/
#include <iostream>
#include <string>
#include "Strategy.h"
 
int main()
{
	Context *c1 = new Context((Strategy*)new OperationAdd());
	Context *c2 = new Context((Strategy*)new OperationSubstract());
	Context *c3 = new Context((Strategy*)new OperationMultiply());
 
	cout <<"1 + 2 = "<<c1->executeStrategy(1, 2) << endl;
	cout <<"1 - 2 = "<< c2->executeStrategy(1, 2) << endl;
	cout <<"1 * 2 = "<< c3->executeStrategy(1, 2) << endl;
 
	delete c1;
	c1 = NULL;
 
	delete c2;
	c2 = NULL;
 
	delete c3;
	c3 = NULL;
	return 0;
}

运行结果:
在这里插入图片描述

要点总结

  • Strategy及其子类为组件提供了一系列可重用的算法,从而可以使得类型在运行时方便地根据需要在各个算法之间进行切换。
  • Strategy模式提供了用条件判断语句以外的另一种选择,消除条件判断语句,就是在解耦合。含有许多条件判断语句的代码通常都需要Strategy模式。
  • 如果Strategy对象没有实例变量,那么各个上下文可以共享同一个strategy对象,从而节省对象开销。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值