文章目录
1. UML类图抽象2. 实例2.1 结果(结论先行)2.2 具体实现2.2.1 Receiver.h2.2.2 ICommand.h2.2.3 ConcreteCmd.h2.2.4 Invoker.h
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