【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);
}
相关推荐
胡萝卜术9 分钟前
从“分数打架”到“排名投票”:为什么你的ChatBI必须用RRF?
算法·设计模式·面试
亦暖筑序21 小时前
Java 8老系统Browser Agent实战:三层拦截把AI操作后台变成可审计流程
java·后端·设计模式
用户805533698031 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
BadBadBad__AK2 天前
线段树维护区间 k 次方和
c++·数学·算法·stl
卷无止境2 天前
Eigen 库如何借助 OpenMP 加速计算
c++·后端
卷无止境2 天前
OpenMPI、MPICH 与 OpenMP:关系、核心概念与架构全解
c++·后端
郝学胜_神的一滴3 天前
CMake 30:循环语法全解|foreach_while双循环精讲、迭代技巧与实战避坑指南
c++·cmake
青禾网络3 天前
Web 前端如何接入 AI 音效生成:从零到可用的完整方案
人工智能·设计模式
ZJPRENO4 天前
吃透软件开发六大设计原则,告别烂代码
设计模式
咖啡八杯4 天前
GoF设计模式——命令模式
java·设计模式·架构