【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);
}
相关推荐
GIS之路44 分钟前
GeoTools 基础概念解析
数据库·设计模式·oracle
归云鹤5 小时前
设计模式二:策略模式 (Strategy Pattern)
设计模式·策略模式
玩代码6 小时前
备忘录设计模式
java·开发语言·设计模式·备忘录设计模式
岁忧7 小时前
(nice!!!)(LeetCode 面试经典 150 题 ) 30. 串联所有单词的子串 (哈希表+字符串+滑动窗口)
java·c++·leetcode·面试·go·散列表
SunkingYang8 小时前
MFC/C++语言怎么比较CString类型最后一个字符
c++·mfc·cstring·子串·最后一个字符·比较
界面开发小八哥8 小时前
MFC扩展库BCGControlBar Pro v36.2新版亮点:可视化设计器升级
c++·mfc·bcg·界面控件·ui开发
R-G-B8 小时前
【15】MFC入门到精通——MFC弹窗提示 MFC关闭对话框 弹窗提示 MFC按键触发 弹窗提示
c++·mfc·mfc弹窗提示·mfc关闭弹窗提示·mfc按键触发 弹窗提示
十秒耿直拆包选手8 小时前
Qt:QCustomPlot类介绍
c++·qt·qcustomplot
珊瑚里的鱼8 小时前
第十三讲 | map和set的使用
开发语言·c++·笔记·visualstudio·visual studio
逑之8 小时前
C++笔记1:命名空间,缺省参数,引用等
开发语言·c++·笔记