文章目录
1. UML类图抽象
2. 实例
2.1 结果(结论先行)
main.cpp
#include "Receiver.h"
#include "ICommand.h"
#include "ConcreteCmd.h"
#include "Invoker.h"
void test()
{
CReceiver* pRcv = new CReceiver();
ICommand* pCmd = new ConcreteCmd(pRcv);
Invoker* pInvk = new Invoker();
pInvk->setCmd(pCmd);
pInvk->execCmd();
delete pRcv;
delete pCmd;
delete pInvk;
pRcv = nullptr;
pCmd = nullptr;
pInvk = nullptr;
}
int main()
{
test();
system("pause");
return 0;
}
2.2 具体实现
2.2.1 Receiver.h
#pragma once
#include <iostream>
using namespace std;
class CReceiver
{
public:
void action() { cout << "执行请求" << endl; }
};
2.2.2 ICommand.h
#pragma once
#include "Receiver.h"
/* 抽象命令类 */
class ICommand
{
public:
ICommand(CReceiver* pReceiver) :m_pReceiver(pReceiver) {}
virtual void exec() = 0;//抽象命令执行接口
protected:
CReceiver* m_pReceiver{ nullptr };
};
2.2.3 ConcreteCmd.h
#pragma once
#include "ICommand.h"
/* 具体命令类 */
class ConcreteCmd :public ICommand
{
public:
ConcreteCmd(CReceiver* pReceiver) :ICommand(pReceiver) {}
virtual void exec() override//具体命令执行接口:调用接受者对应的动作接口
{
m_pReceiver->action();
}
};
2.2.4 Invoker.h
#pragma once
#include "ICommand.h"
/* 命令发起者,要求该命令执行这个请求 */
class Invoker
{
public:
/* 设置命令 */
void setCmd(ICommand* pCmd) { m_pCmd = pCmd; };
/* 执行命令 */
void execCmd() { m_pCmd->exec(); }
private:
ICommand* m_pCmd{ nullptr };
};
此为《大话设计模式》学习心得系列 P242~~
命令模式相关链接:
《大话设计模式》C++实现:23 命令模式(一)基础版
《大话设计模式》C++实现:23 命令模式(二)进阶版
《大话设计模式》C++实现:23 命令模式(二)进阶版2