【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);
}
相关推荐
青禾网络1 小时前
Web 前端如何接入 AI 音效生成:从零到可用的完整方案
人工智能·设计模式
ZJPRENO1 天前
吃透软件开发六大设计原则,告别烂代码
设计模式
咖啡八杯1 天前
GoF设计模式——命令模式
java·设计模式·架构
花椒技术2 天前
HJPusher / HJPlayer SDK 实践:我们为什么把直播推播链路拆成一套可复用能力
设计模式·harmonyos·直播
卷无止境2 天前
C++ 的Eigen 库全解析
c++
卷无止境2 天前
现代 C++特性大盘点:一门脱胎换骨的老语言
c++·后端
郝学胜_神的一滴2 天前
CMake 27:缓存变量的特性、语法、类型与实操全解
c++·cmake
艺艺生辉2 天前
迭代器模式-"我也想被增强for循环"
设计模式
咖啡八杯4 天前
GoF设计模式——策略模式
java·后端·spring·设计模式