【C++设计模式】策略模式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zxh2075/article/details/82875863
#ifndef __STRATEGY_H__
#define __STRATEGY_H__

//策略模式(Strategy):它定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法的变化不会影响到使用算法的客户。
//策略模式是很简单的设计模式,就是面向对象编程中多态的完整体现。
//我们可以看到客户端在使用的时候,使用哪种策略是由客户端决定的。


//抽象算法接口
class iStrategy
{
public:
	virtual void algorithm(int a, int b) = 0;
};

//策略A
class StrategyA : public iStrategy
{
public:
	virtual void algorithm(int a, int b);
};

//策略B
class StrategyB : public iStrategy
{
public:
	virtual void algorithm(int a, int b);
};

//策略C
class StrategyC : public iStrategy
{
public:
	virtual void algorithm(int a, int b);
};

//上下文类,定义客户端使用的接口并维护一个具体策略的实例
class Context
{
public:
	Context(iStrategy *sgy);	

	virtual ~Context();

	void execute(int a, int b);

private:

	iStrategy *m_sgy;
};

void TestStrategy();

#endif
#include <stdio.h>
#include "Strategy.h"

void StrategyA::algorithm(int a, int b)
{
	printf("a + b = %d \n", a+b);
}

void StrategyB::algorithm(int a, int b)
{
	printf("a - b = %d \n", a-b);
}

void StrategyC::algorithm(int a, int b)
{
	printf("a * b = %d \n", a*b);
}

Context::Context(iStrategy *sgy)
{
	m_sgy = sgy;
}

Context::~Context()
{

}

void Context::execute(int a, int b)
{
	m_sgy->algorithm(a,b);
}

void TestStrategy()
{
	iStrategy * sgy1 = new StrategyA();
	Context *con1 = new Context(sgy1);
	con1->execute(5,3);

	iStrategy * sgy2 = new StrategyC();
	Context * con2 = new Context(sgy2);
	con2->execute(5,3);
}

猜你喜欢

转载自blog.csdn.net/zxh2075/article/details/82875863