c++的策略模式,就是多态

一、定义:

策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。

策略模式让算法独立于使用它的客户而独立变化。

二,核心

复制代码
抽象策略(抽象基类)(Strategy): 抽象策略类。
具体策略(具体子类)(ConcreteStrategy):封装了继续相关的算法和行为。
环境角色(Context):持有一个策略类的引用,最终给客户端调用。

三,UML类图

用法示例:

复制代码
1.空调支持3种模式。冷风模式(coldWind), 热风模式(hotWind),无风模式(noWind)。
1.1当选择coldWind模式,将输送冷风;
1.2当选择hotWind模式,将输送热风;
1.3在选择noWind模式时,空调什么都不做。

这里coldWind, hotWind, noWind 其实就是ConcreteStrategy。 myStrategy 是抽象策略类。 所以我们开始这么封装我们策略类

myStrategy.h

复制代码
#pragma once
#include <iostream>
using namespace std;

// 抽象策略角色(Strategy)
//抽象基类写了两个虚函数
class myStrategy
{
public:		
	myStrategy() { std::cout << "new myStrategy" << endl; };
	virtual ~myStrategy() { std::cout << "delete myStrategy!" << endl; };

	virtual void blowWind() = 0;
};

//具体策略角色(ConcreteStrategy)
class coldWind: public myStrategy
{
public:
	coldWind() { std::cout << "new coldWind" << endl; };
	~coldWind() { std::cout << "delete clod wind!" << endl; };

	void blowWind()
	{
		std::cout << "Blowing clod wind!" << endl;
	}
};

//具体策略角色(ConcreteStrategy)
//继承基类实现热风
class hotWind: public myStrategy
{
public:
	hotWind() { std::cout << "new hotWind" << endl; };
	~hotWind() { std::cout << "delete hot wind!" << endl; };

	void blowWind()
	{
		std::cout << "Blowing hot wind!" << endl;
	}
};
//具体策略角色(ConcreteStrategy)
//继承基类实现无风
class noWind: public myStrategy
{
public:
	noWind() { std::cout << "new noWind" << endl; };
	~noWind() { std::cout << "delete no wind!" << endl; };

	void blowWind()
	{
		std::cout << "Blowing no wind!" << endl;
	}
};

context.h

使用基类指针调用子类的方法

复制代码
#pragma once

//环境角色(Context)
#include "myStrategy.h"

class windMode
{
public:
	windMode(myStrategy* wind);
	~windMode();

	void blowWind();
	void freePtr();	
private:
	//环境角色持有的策略类指针(或引用)
	myStrategy* m_wind;			
};

context.cpp

复制代码
#include "context.h"

windMode::windMode(myStrategy* wind)
	: m_wind(wind)
{
}

windMode::~windMode()
{
}

void windMode::blowWind()
{
	m_wind->blowWind();
}

void windMode::freePtr()
{
	if (m_wind)
	{
		std::cout << "delete memory" << endl;
		delete m_wind;
		m_wind = NULL;
	}
}

用基类指针调用子类方法

main.cpp

复制代码
#include <iostream>
#include "windMode.h"
using namespace std;
int main()
{
	//策略模式使用
	windMode* hot_Wind = new windMode(new hotWind());
	windMode* cold_Wind = new windMode(new coldWind());
	windMode* no_Wind = new windMode(new noWind());

	hot_Wind->blowWind();
	cold_Wind->blowWind();
	no_Wind->blowWind();

	hot_Wind->freePtr();
	cold_Wind->freePtr();
	no_Wind->freePtr();

	return 0;
}
相关推荐
apocelipes1 天前
常用编程语言和库的正则表达式性能对比
c语言·c++·python·性能优化·golang·开发工具和环境
郝学胜_神的一滴3 天前
CMake 034:生成器表达式:解耦构建时序、精简分支逻辑的终极利器
c++·cmake
见过夏天3 天前
C++ 基础入门完全指南
c++
用户805533698034 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
BadBadBad__AK5 天前
线段树维护区间 k 次方和
c++·数学·算法·stl
卷无止境5 天前
Eigen 库如何借助 OpenMP 加速计算
c++·后端
卷无止境6 天前
OpenMPI、MPICH 与 OpenMP:关系、核心概念与架构全解
c++·后端
郝学胜_神的一滴6 天前
CMake 30:循环语法全解|foreach_while双循环精讲、迭代技巧与实战避坑指南
c++·cmake
卷无止境8 天前
C++ 的Eigen 库全解析
c++
卷无止境8 天前
现代 C++特性大盘点:一门脱胎换骨的老语言
c++·后端