当前位置: 首页 > news >正文

行为型模式

模板方法模式

#include<iostream>
#include<string>
using namespace std;/*案例:写简历内容:最近有个招聘会,可以带上简历去应聘了。但是,其中有一家公司不接受简历,而是给应聘者发了一张简历表,上面有基本信息、教育背景、工作经历等栏,让应聘者按照要求填写完整。每个人拿到这份表格后,就开始填写。如果用程序实现这个过程,该如何做呢?一种方案就是用模板方法模式:定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
*/// 简历(抽象)
class Resume
{
protected:virtual void writeBasicInfo() = 0;virtual void writeEducation() = 0;virtual void writeWorkExperience() = 0;public:// 模板方法核心void FillResume(){writeBasicInfo();writeEducation();writeWorkExperience();}virtual ~Resume() {};	// 析构函数
};// 简历A(具体)
class ResumeA : public Resume
{
protected:void writeBasicInfo(){cout << "简历A: 基本信息, ";}void writeEducation(){cout << "教育背景, ";}void writeWorkExperience(){cout << "工作经验 (越详细越好)." << endl;}
};// 简历B(具体)
class ResumeB : public Resume
{
protected:void writeBasicInfo(){cout << "简历B: 基本信息, ";}void writeEducation(){cout << "教育背景, ";}void writeWorkExperience(){cout << "工作经验 (请简要概况)." << endl;}
};int main()
{// 写简历AResume* r1 = new ResumeA;r1->FillResume();// 写简历BResume* r2 = new ResumeB;r2->FillResume();delete r1;delete r2;system("pause");return 0;
}

命令模式

#include<iostream>
#include<string>
#include<vector>
using namespace std;/*案例:客人点餐1. 客人发出命令,让厨师做饭2. 客人发出命令,让厨师取消做饭3. 客人发出命令,让厨师煮面4. 客人发出命令,让厨师取消煮面
*/// 厨师(具体)
class Chef
{
public:// 做饭void makeMeals(){cout << "正在做饭中..." << endl;}// 取消做饭void cancelMeals(){cout << "已取消做饭!" << endl;}// 煮面void makeNoodles(){cout << "正在煮面中..." << endl;}// 取消煮面void cancelNoodles(){cout << "已取消煮面!" << endl;}
};// 命令(抽象)
class Command
{
protected:Chef* chef;		// 用来保存一个厨师public:virtual void executeCommand() = 0;		// 执行命令virtual void cancelCommand() = 0;		// 取消命令virtual ~Command() {};
};// 关于做饭的命令(具体)
class AboutMealsCommand : Command
{
public:// 构造函数,列表初始化:每构造一条命令,都要对应着一个厨师,让他执行这个命令AboutMealsCommand(Chef* c){this->chef = c;}// 执行命令void executeCommand(){chef->makeMeals();			// 让厨师做饭}// 取消命令void cancelCommand(){chef->cancelMeals();		// 让厨师取消做饭}
};// 关于煮面的命令(具体)
class AboutNoodlesCommand : Command
{
public:// 构造函数,列表初始化:每构造一条命令,都要对应着一个厨师,让他执行这个命令AboutNoodlesCommand(Chef* c){this->chef = c;}// 执行命令void executeCommand(){chef->makeNoodles();			// 让厨师煮面}// 取消命令void cancelCommand(){chef->cancelNoodles();		// 让厨师取消煮面}
};// 客人(具体)
class Customer
{
private:vector<Command*> commandQueue;		// 命令队列,用来存放这个顾客的一系列命令public:// 添加命令void add(Command* command){commandQueue.push_back(command);		// 将当前这一条的下单命令添加到命令队列中cout << "客人发出了一条命令" << endl;}// 移除命令void remove(Command* command){for (auto iter = commandQueue.begin(); iter != commandQueue.end(); iter++){// 将当前命令从命令队列中删除if ((*iter) == command){commandQueue.erase(iter);break;}}cout << "客人取消了一条命令" << endl;}// 确认订单void confirm(){for (auto command : commandQueue){command->executeCommand();}commandQueue.clear();}// 取消订单void cancel(){for (auto command : commandQueue){command->cancelCommand();}commandQueue.clear();}
};int main()
{// 招牌一个厨师Chef* chef = new Chef();// 制定好跟"做饭"相关的"命令/规则",具体包括,做饭与取消做饭两个功能Command* mealsCommand = (Command*) new AboutMealsCommand(chef);// 制定好跟"煮面"相关的"命令/规则",具体包括,做饭与取消做饭两个功能Command* noodlesCommand = (Command*) new AboutNoodlesCommand(chef);// 来了一位顾客Customer* customer = new Customer();// 顾客下达一系列的命令,想要点单customer->add(mealsCommand);customer->add(noodlesCommand);customer->remove(mealsCommand);// 顾客确认订单customer->confirm();// 顾客下达了一系列的命令,想要取消点单customer->add(noodlesCommand);// 顾客取消了订单customer->cancel();delete customer;delete chef;delete mealsCommand;delete noodlesCommand;system("pause");return 0;
}

责任链模式

#include<iostream>
#include<string>
using namespace std;/*案例:员工请假内容:当员工申请请假1天以内,由组长批准即可(处理者为组长)当员工申请请假超过3天,需要由经理批准(处理者为经理)当员工申请请假超过7天,需要由老板批准(处理者为老板)
*/// 处理者(抽象)
class Handler
{
protected:Handler* nextHanler;	// 维护下一个处理者的指针。万一当前处理者没有权力处理时,就交给下一个处理者进行处理。public:// 构造函数,列表初始化Handler() : nextHanler(nullptr) { cout << "初始化成功!" << endl; }// 设置下一个处理者是谁(如果不设置,就默认没有关联)void setNextHandler(Handler* next){this->nextHanler = next;}// 具体的处理请求virtual void handleRequest(int days) = 0;virtual ~Handler() {};
};// 组长(具体)
class GroupLeader : public Handler
{
public:void handleRequest(int days){cout << "组长回复:";if (days <= 1){cout << "同意请假!" << endl;}else{cout << "请假太久了,你去找经理请假。" << endl;if (this->nextHanler != nullptr) nextHanler->handleRequest(days);}}
};// 经理(具体)
class Manager : public Handler
{
public:void handleRequest(int days){cout << "经理回复:";if (days <= 3){cout << "同意请假!" << endl;}else{cout << "请假太久了,你去找老板请假。" << endl;if (this->nextHanler != nullptr) nextHanler->handleRequest(days);}}
};// 老板(具体)
class Boss : public Handler
{
public:void handleRequest(int days){cout << "老板回复:";if (days <= 7){cout << "同意请假!" << endl;}else{cout << "请假太久了,不行!" << endl;if (this->nextHanler != nullptr) nextHanler->handleRequest(days);}}
};int main()
{// 实例化一个组长、一个经理、一个老板Handler* groupLeader = new GroupLeader;Handler* manager = new Manager;Handler* boss = new Boss;// 组装链groupLeader->setNextHandler(manager);manager->setNextHandler(boss);// 请假int days;// ------------------days = 1;cout << "想要请假" << days << "天" << endl;groupLeader->handleRequest(days);// ------------------days = 3;cout << "想要请假" << days << "天" << endl;groupLeader->handleRequest(days);// ------------------days = 7;cout << "想要请假" << days << "天" << endl;groupLeader->handleRequest(days);// ------------------days = 30;cout << "想要请假" << days << "天" << endl;groupLeader->handleRequest(days);delete groupLeader;delete manager;delete boss;system("pause");return 0;
}

策略模式

#include<iostream>
#include<string>
using namespace std;// 策略(抽象)
class Strategy
{
public:virtual int execute(int left, int right) = 0;
};// 加法策略(具体)
class Add : public Strategy
{
public:int execute(int left, int right){return left + right;}
};// 减法策略(具体)
class Sub : public Strategy
{
public:int execute(int left, int right){return left - right;}
};// 乘法策略(具体)
class Mul : public Strategy
{
public:int execute(int left, int right){return left * right;}
};// 除法策略(具体)
class Div : public Strategy
{
public:int execute(int left, int right){if (right == 0){cout << "除数不能为零!" << endl;return 0;}return left / right;}
};// 策略容器(具体)
class Container
{
private:Strategy* strategy;		// 维护一个策略public:// 设置策略void setStrategy(Strategy* s){this->strategy = s;}// 执行某策略的功能int executeStrategy(int left, int right){return strategy->execute(left, right);}
};int main()
{// 实例化一个策略容器Container* container = new Container;int left, right;char symbol;Strategy* strategy = nullptr;while (true){cout << "(Count) >>> ";// 获取用户输入cin >> left >> symbol >> right;// 根据用户选择,向策略容器里面添加合适的策略switch (symbol){case '+':strategy = new Add;container->setStrategy(strategy);break;case '-':strategy = new Sub;container->setStrategy(strategy);break;case '*':strategy = new Mul;container->setStrategy(strategy);break;case '/':strategy = new Div;container->setStrategy(strategy);break;}// 执行策略容器里面的策略cout << container->executeStrategy(left, right) << endl;delete strategy;}system("pause");return 0;
}

观察者模式

#include<iostream>
#include<string>
#include<vector>
using namespace std;/*案例:员工摸鱼————通过观察老板是否出现,员工做出不同的反应(摸鱼或努力工作)
*/// 声明一个老板类
class Boss;// 实现一个员工类(具体)
class Employee
{
private:string m_name;		// 维护员工自己的姓名public:// 构造函数,初始化列表Employee(string name) : m_name(name) {};// 更新"老板是否来了"的动作消息,做出相应的反应void updateInfomation(string info){cout << m_name << "收到情报:" << info << endl;if (info == "老板来了"){cout << "--> 开启工作模式" << endl;}else if (info == "老板走了"){cout << "--> 开启摸鱼模式" << endl;}}
};// 实现一个老板类(具体)
class Boss
{
private:string information;							// 保存一个老板的动作消息vector<Employee*> employeeContainer;		// 员工容器,用来存放老板手下的所有员工public:// 添加员工void addEmployee(Employee* employee){this->employeeContainer.push_back(employee);}// 老板设置自己的动作消息void setActionInfo(string info){this->information = info;		// 老板设置自己的动作消息notify();						// 发出通知(老板更新了自己的动作)}// 发出通知void notify(){for (auto v : employeeContainer){v->updateInfomation(this->information);		// 更新员工的消息,从而实现监控(观测)老板}}
};int main()
{// 实例化一个老板(被观察者)Boss* boss = new Boss;// 实例化一些员工(观察者)Employee* emp1 = new Employee("小明");Employee* emp2 = new Employee("老张");Employee* emp3 = new Employee("老李");// 让老板去招聘上面这些员工(建立关联)boss->addEmployee(emp1);boss->addEmployee(emp2);boss->addEmployee(emp3);// 老板设置动作消息// 当老板设置动作消息成功后,将会自动发出通知,更新员工的消息,员工根据消息内容选择是否摸鱼boss->setActionInfo("老板来了");boss->setActionInfo("老板走了");delete boss;delete emp1;delete emp2;delete emp3;system("pause");return 0;
}

访问者模式

#include<iostream>
#include<string>
using namespace std;/*案例:这里实现一个不同职业的人去医院和餐厅的例子来说明访问者模式在小镇上有一个医院和一个餐厅,每天都会有不同的人访问这两个地方,由于访问者不同到这两个地方要做的事也有区别。医生去医院是为了工作给病人看病,厨师去医院是为了检查身体,医生去餐厅是为了吃饭,厨师去餐厅是为了工作给客人烹饪菜肴。
*/// 声明"地方类"
class Place;// 访问者(抽象访问者)
class Visitor
{
public:virtual void visitHospital(Place* place) = 0;virtual void visitResteraunt(Place* place) = 0;virtual ~Visitor() {};
};// 地方(抽象地方)
class Place
{
protected:string placeName;		// 保存地方的名字public:string getName()		// 获得地方的名字{return this->placeName;}// 让这个地方接收访问者virtual void accept(Visitor* visitor) = 0;virtual ~Place() {}
};// 医院(具体地方)
class Hospital : public Place
{
public:Hospital(string name){this->placeName = name;}// 接受访问者的访问,访问者将访问医院内部void accept(Visitor* visitor){visitor->visitHospital(this);		// 访问者访问医院内部}
};// 餐馆(具体地方)
class Resteraunt : public Place
{
public:Resteraunt(string name){this->placeName = name;}// 接受访问者的访问,访问者将访问餐馆内部void accept(Visitor* visitor){visitor->visitResteraunt(this);		// 访问者访问餐馆内部}
};// 医生(具体访问者)
class Doctor : public Visitor
{
public:void visitHospital(Place* place){cout << "医生访问" << place->getName() << "是为了治疗病人" << endl;}void visitResteraunt(Place* place){cout << "医生访问" << place->getName() << "是为了吃一顿饭" << endl;}
};// 厨师(具体访问者)
class Chef : public Visitor
{
public:void visitHospital(Place* place){cout << "厨师访问" << place->getName() << "是为了治病" << endl;}void visitResteraunt(Place* place){cout << "厨师访问" << place->getName() << "是为了做菜" << endl;}
};int main()
{// 实例化一个医院Place* hospital = new Hospital("丽江市第一人名医院");// 实例化一个餐馆Place* resteraunt = new Resteraunt("幸福餐馆");// 实例化一个医生(访问者)Visitor* doctor = new Doctor();// 实例化一个厨师(访问者)Visitor* chef = new Chef();// 医生访问医院(医院接收医生的拜访)hospital->accept(doctor);// 医生访问餐馆(餐馆接收医生的拜访)resteraunt->accept(doctor);// 厨师访问医院(医院接收厨师的拜访)hospital->accept(chef);// 厨师访问餐馆(餐馆接收厨师的拜访)resteraunt->accept(chef);delete hospital;delete resteraunt;delete doctor;delete chef;system("pause");return 0;
}

中介者模式

#include<iostream>
#include<string>
using namespace std;class Role;		// 声明角色// 中介者(抽象中介者)
class Mediator
{
protected:Role* hr;Role* student;public:void set_HR(Role* hr){this->hr = hr;}void set_Student(Role* student){this->student = student;}virtual void match() = 0;
};// 角色(抽象角色)
class Role
{
protected:string name;			// 角色名字string offer;			// offer的岗位或内容Mediator* mediator;		// 保存一个中介,该角色需要求助"中介"public:string getName(){return this->name;}string getOffer(){return this->offer;}// 进行配对virtual void match(Role* role) = 0;
};// 学生(具体角色)
class Student : public Role
{
public:Student(string name, string offer, Mediator* mediator){this->name = name;this->offer = offer;this->mediator = mediator;}void match(Role* role){mediator->set_HR(role);mediator->set_Student(this);mediator->match();}
};// 人事HR(具体角色)
class HR : public Role
{
public:HR(string name, string offer, Mediator* mediator){this->name = name;this->offer = offer;this->mediator = mediator;}void match(Role* role){mediator->set_HR(this);mediator->set_Student(role);mediator->match();}
};// 猎聘App(具体中介者)
class LiepinApp : public Mediator
{
public:void match(){cout << "------------------" << endl;cout << hr->getName() << "提供岗位:" << hr->getOffer() << endl;cout << student->getName() << "需求职位:" << student->getOffer() << endl;if (hr->getOffer() == student->getOffer()){cout << "配对成功!" << endl;}else{cout << "配对失败!" << endl;}cout << "------------------" << endl;}
};int main()
{// 实例化 中介 ———— 猎聘AppMediator* app1 = new LiepinApp;// 实例化 人事HRRole* hr = new HR("花儿姐", "软件工程师", app1);		// 使用 app1app1->set_HR(hr);		// 把自己的招聘信息挂到网上// 实例化 学生Role* student = new Student("小明", "机械工程师", app1);	// 使用 app1app1->set_Student(student);		// 把自己的求职信息挂到网上// 让 app1 进行匹配 app1->match();delete app1;delete hr;delete student;system("pause");return 0;
}

备忘录模式

// 待补充

状态模式

// 待补充

迭代器模式

// 待补充

解释器模式

// 待补充
http://www.lryc.cn/news/350282.html

相关文章:

  • AI大模型日报#0515:Google I/O大会、 Ilya官宣离职、腾讯混元文生图大模型开源
  • 计算机网络-负载均衡算法
  • Excel Module: Iteration #1 EasyExcel生成下拉列表模版时传入动态参数查询下拉数据
  • 【回溯算法】【Python实现】TSP旅行售货员问题
  • Java处理xml
  • 软考中级-软件设计师 (十一)标准化和软件知识产权基础知识
  • pytest教程-46-钩子函数-pytest_sessionstart
  • Windows内核函数 - ASCII字符串和宽字符串
  • 从零开始学习MySQL 事务处理
  • 字符数组以及字符串相关的几个函数
  • AOP面向切面编程
  • C# WinForm —— 15 DateTimePicker 介绍
  • SpringBoot中六种批量更新Mysql 方式效率对比
  • 【SpringBoot】SpringBoot整合jasypt进行重要数据加密
  • 【Go语言入门学习笔记】Part1.梦开始的地方
  • 数据特征降维 | 主成分分析(PCA)附Python代码
  • 当服务实例出现故障时,Nacos如何处理?
  • 遥感数据集制作(Potsdam数据集为例):TIF图像转JPG,TIF标签转PNG,图像重叠裁剪
  • 根据web访问日志,封禁请求量异常的IP,如IP在半小 时后恢复正常则解除封禁
  • 2.go语言初始(二)
  • MQTT对比HTTP
  • 暴力数据结构之二叉树(堆的相关知识)
  • 死锁调试技巧:工作线程和用户界面线程
  • 蓝桥杯-外卖店优先级(简单写法)
  • VueRouter使用总结
  • Flink checkpoint 源码分析- Checkpoint snapshot 处理流程
  • Leaflet.canvaslabel在Ajax异步请求时bindPopup无效的解决办法
  • Go 处理错误
  • python读取excel数据写入mysql
  • flutter日期选择器仅选择年、月