【29】c++设计模式——>策略模式

策略模式

C++中的策略模式(Strategy Pattern)是一种行为型设计模式,它允许在运行时选择算法的行为。策略模式通过将算法封装成独立的类,并且使它们可以互相替换,从而使得算法的变化独立于使用算法的客户端。

策略模式通常由三个核心组件组成:

1.策略接口(Strategy Interface):定义了所有具体策略类必须实现的方法,通常是一个纯虚函数接口。

2.具体策略类(Concrete Strategies):实现了策略接口,并提供了不同的算法实现。

3.环境类(Context Class):包含一个指向策略接口的指针成员,用于调用具体策略类的算法。

示例代码

cpp 复制代码
#include<iostream>
#include<string>
using namespace std;

class Strategy
{
public:
	virtual void execute() = 0;
};

class ConcreteStrategyA : public Strategy
{
public:
	void execute() override
	{
		cout << "================_i am A strategy_=======================" << endl;
	}
};

class ConcreteStrategyB : public Strategy
{
public:
	void execute() override
	{
		cout << "================_i am B strategy_=======================" << endl;
	}
};

class Context
{
public:
	void call(int type)
	{
		if (s != nullptr)
		{
			delete s;
		}
		switch (type)
		{
		case 1:
			s = new ConcreteStrategyA;
			break;
		case 2:
			s = new ConcreteStrategyB;
			break;
		default:
			break;
		}
		s->execute();
	}
	~Context()
	{
		if (s != nullptr)
		{
			delete s;
		}
	}

private:
	Strategy *s = nullptr;
};


int main()
{
	Context *c = new Context;
	c->call(1);
	c->call(2);
}
相关推荐
霸道流氓气质22 分钟前
SpringBoot中设计模式组合使用示例-策略、模板、观察者、门面、工厂、单例。
spring boot·后端·设计模式
hehelm35 分钟前
IO 多路复用 — Reactor
linux·服务器·网络·数据库·c++
灵晔君1 小时前
【C++】二叉搜索树
开发语言·c++
ttod_qzstudio2 小时前
【软考设计模式】观察者模式:一对多依赖的自动通知与订阅解耦精讲
观察者模式·设计模式
鱼子星_2 小时前
【C++】内存管理:内存分布,new/delete的使用及细节处理,new/delete的底层,定位new表达式
开发语言·c++·笔记
鱼子星_2 小时前
【C++】string(上):string的基本使用
c++·笔记·字符串
神仙别闹3 小时前
编写基于C++ Huffman 算法的无损压缩程序和解压程序
java·c++·算法
炸膛坦客3 小时前
单片机/C/C++八股:(二十三)#define 和 typedef 的区别
c语言·c++·单片机
旖-旎4 小时前
《LeetCode 646 最长数对链 || LeetCode 1143 最长公共子序列》
c++·算法·leetcode·动态规划
ttod_qzstudio4 小时前
【软考设计模式】命令模式:请求封装与调用接收解耦的精讲
设计模式·命令模式