【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);
}
相关推荐
麻瓜code32 分钟前
用策略模式写一个可断点续传的状态机
策略模式
小小bugbug1 小时前
带工作窃取的线程池
c++·线程池
南风841118 小时前
C++ 四种强制类型转换详解
c++
微笑星河q18 小时前
C++STL【vector】常用接口函数使用和迭代器失效问题
开发语言·c++
wy_hhxx20 小时前
《Agent设计模式 图解可复用智能体架构》上篇内容整理
设计模式·架构·ai agent
AAA修煤气灶刘哥21 小时前
DSH Super-agent 双层架构:如何兼顾后台执行与持续响应
人工智能·后端·设计模式
HaiXCoder21 小时前
C++ 表达式怎么读:从一行代码到类型、值类别和生命周期
c++
kyle~1 天前
因子图优化(Factor Graph Optimization)
c++·算法·机器人·传感器
geats人山人海1 天前
现代c++4.1
java·开发语言·c++
lunar_coder1 天前
【算法】前缀和:把 O(n) 的重复劳动变成 O(1) 的一次查询
c++·算法