【设计模式】策略模式

来源:爱编程的大丙

策略模式定义一系列的算法,并且将每种算法都放入到独立的类中,在实际操作中使这些算法对象可以互相替换。

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

class AbstractStrategy {
public:
	virtual void fight(bool isfar = false) = 0;
	virtual ~AbstractStrategy() {}
};

class YiDang :public AbstractStrategy {
public:
	void fight(bool isfar = false)override {
		cout << "***现在是使用的一档:";
		if (isfar) {
			cout << "橡胶机关枪" << endl;
		}
		else {
			cout << "橡胶·攻城炮" << endl;
		}
	}
};

class ErDang :public AbstractStrategy {
public:
	void fight(bool isfar = false)override {
		cout << "***切换二档:";
		if (isfar) {
			cout << "橡胶Jet火箭" << endl;
		}
		else {
			cout <<"橡胶Jet·铳乱打" << endl;
		}
	}
};

class SanDang :public AbstractStrategy {
public:
	void fight(bool isfar = false)override {
		cout << "***切换三档:";
		if (isfar) {
			cout << "橡胶巨人回旋弹" << endl;
		}
		else {
			cout << "橡胶巨人战斧"  << endl;
		}
	}
};

class SiDang :public AbstractStrategy {
public:
	void fight(bool isfar = false)override {
		cout << "***切换四档:";
		if (isfar) {
			cout << "橡胶狮子火箭炮" << endl;
		}
		else {
			cout << "橡胶犀牛榴弹炮" << endl;
		}
	}
};

class WuDang :public AbstractStrategy {
public:
	void fight(bool isfar = false)override {
		cout << "*** 切换成五挡: 变成尼卡形态可以把物体变成橡胶, 并任意改变物体的形态对其进行攻击!!!"<<endl;
	}
};
//难度级别
enum class Level :char {Easy,Normal,Hard,Experts,Professional};
//路飞
class Luffy {
public:
	void fight(Level level, bool isfar = false) {
		if (m_strategy) {
			delete m_strategy;
			m_strategy = nullptr;
		}
		switch (level)
		{
		case Level::Easy:
			m_strategy = new YiDang;
			break;
		case Level::Normal:
			m_strategy = new ErDang;
			break;
		case Level::Hard:
			m_strategy = new SanDang;
			break;
		case Level::Experts:
			m_strategy = new SiDang;
			break;
		case Level::Professional:
			m_strategy = new WuDang;
			break;
		default:
			break;
		}
		m_strategy->fight(isfar);
	}
	~Luffy() {
		delete m_strategy;
	}

private:
	AbstractStrategy* m_strategy = nullptr;
};

int main() {
	Luffy* luffy = new Luffy;
	cout << "--- 在香波地群岛遇到了海军士兵: " << endl;
	luffy->fight(Level::Easy);
	cout << "--- 在魔谷镇遇到了贝拉米: " << endl;
	luffy->fight(Level::Normal);
	cout << "--- 在司法岛遇到了罗布·路奇: " << endl;
	luffy->fight(Level::Hard);
	cout << "--- 在德雷斯罗萨遇到了多弗朗明哥: " << endl;
	luffy->fight(Level::Experts);
	cout << "--- 在鬼岛遇到了凯多: " << endl;
	luffy->fight(Level::Professional);
	delete luffy;

	return 0;
}
相关推荐
Zane19942 天前
一个 new 就能创建对象,为什么还要拆出单例、工厂、建造者、原型四种模式?
设计模式
怕浪猫3 天前
一行命令复刻爆款视频,我把 Hypit 从安装跑到了出片
人工智能·设计模式·程序员
Zane19943 天前
函数式编程里的函数,其实不是你天天写的那个函数——三大编程范式的边界在哪
设计模式
Zane19944 天前
策略模式现在该不该上?一次讲清楚过度设计和设计不足怎么找平衡
设计模式
她说..4 天前
常见设计模式-模板方法模式
java·spring·设计模式·springboot
xiaofeiyang1504 天前
第六章 · 桥接 — 三支毛笔,画出九种颜色
设计模式
Shadow(⊙o⊙)5 天前
OTOL设计模式 One Thread One Loop
服务器·网络·设计模式
sarasuki5 天前
如何让LLM 能在半夜偷偷打开网易云呢?
人工智能·设计模式·agent
小王师傅666 天前
【设计模式】装饰模式(四):框架源码实战——从 Java I/O 到 Spring 到 MyBatis
java·设计模式
执明wa6 天前
Android RecyclerView 多类型, 多种 Item
android·xml·开发语言·设计模式·android studio