设计模式之策略模式-软件设计的锦囊妙计!

一、策略模式的概念

策略模式是一种行为模式,它通过对一系列的算法(或者行为)加以封装,并为这些算法(或者行为)定义统一的抽象算法(或者行为)接口, 具体子类继承该抽象算法(或者行为)接口对所有的算法(或者行为)加以封装和实现,调用者去自由的选择使用哪个算法(或者行为)。

二、策略模式使用场景

1、一个系统需要动态地在几种算法(或者行为)中选择一种时,可以使用策略模式。
2、当一个对象有很多的行为,为避免使用过多的条件判断语句,可以使用策略模式来实现。

三、策略模式构建方法

1、策略抽象类(Strategy)

策略抽象类给策略具体类提供统一的共同接口和方法。

2、策略具体类(ConcreteStrategy)

策略具体类继承策略抽象类,用于实现策略抽象父类中的共同接口和方法。

3、策略的容器类(Context)

策略的外部封装类, 根据不同的策略执行不同的行为。

四、策略模式的示例

// StrategyPattern.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <string>

using namespace std;

#define DELETE_PTR(p) {if(p!=nullptr){delete (p); (p)=nullptr;}}

// 策略算法基类
class AlgorithmBase
{
public:
	virtual void algorithmName() = 0;
};

// 冒泡排序算法
class BubbleSort : public AlgorithmBase
{
public:
	virtual void algorithmName()
	{
		cout << "调用冒泡排序算法" << endl;
	}
};

// 选择排序算法
class SelectSort : public AlgorithmBase
{
public:
	virtual void algorithmName()
	{
		cout << "调用选择排序算法" << endl;
	}
};

// 插入排序算法
class InsertSort : public AlgorithmBase
{
public:
	virtual void algorithmName()
	{
		cout << "调用插入排序算法" << endl;
	}
};

// 策略模式的容器类
class ContextAlgorithm
{
public:
	ContextAlgorithm(AlgorithmBase *pAlgorithmBase)
	{
		if (pAlgorithmBase != nullptr)
		{
			m_pAlgorithmBase = pAlgorithmBase;
		}
	}

	~ContextAlgorithm()
	{
		DELETE_PTR(m_pAlgorithmBase);
	}

	void choiceAlgorithm()
	{
		cout << "=====客户端通过策略模式的容器类调用算法====" << endl;
		m_pAlgorithmBase->algorithmName();
	}

private:
	AlgorithmBase *m_pAlgorithmBase;
};



int main()
{
	cout << "--------------------策略模式-----------------------" << endl;
	cout << "--------直接调用各个算法类------" << endl;
	AlgorithmBase *pAlgorithmBase = nullptr;
	pAlgorithmBase = new BubbleSort;
	pAlgorithmBase->algorithmName();
	DELETE_PTR(pAlgorithmBase);

	pAlgorithmBase = new SelectSort;
	pAlgorithmBase->algorithmName();
	DELETE_PTR(pAlgorithmBase);

	pAlgorithmBase = new SelectSort;
	pAlgorithmBase->algorithmName();
	DELETE_PTR(pAlgorithmBase);

	//cout << "--------调用策略模式的容器类------" << endl;
	pAlgorithmBase = new BubbleSort;
	ContextAlgorithm *pContextAlgorithm = new ContextAlgorithm(pAlgorithmBase); //以调用冒泡排序为例
	pContextAlgorithm->choiceAlgorithm();
	//DELETE_PTR(pAlgorithmBase); // 不需要释放了,已经在ContextAlgorithm中析构释放
	DELETE_PTR(pContextAlgorithm);

    std::cout << "Hello World!\n";
	getchar();
}

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

五、策略模式的优缺点

优点:

1、策略模式提供了管理算法族的办法,算法之间可以自由切换。
2、策略模式可以避免使用多重条件判断。
3、策略模式可以进行良好的算法扩展。

缺点:

1、策略过多,导致策略类过多,调用者需要理解调用自己需要的一种算法类。
2、所有的策略类都要暴露给调用者才行。

六、题外话

1、冒泡排序

2、选择排序

3、插入排序

4、快速排序

能力有限,如有错误,多多指教。。。

扫描二维码关注公众号,回复: 10524742 查看本文章
发布了157 篇原创文章 · 获赞 135 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/toby54king/article/details/104571680