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;
}
#pragma once
#include <iostream>
using namespace std;
class CReceiver
{
public:
void action() { cout << "執行請求" << endl; }
};
#pragma once
#include "Receiver.h"
/* 抽象命令類 */
class ICommand
{
public:
ICommand(CReceiver* pReceiver) :m_pReceiver(pReceiver) {}
virtual void exec() = 0;//抽象命令執行介面
protected:
CReceiver* m_pReceiver{ nullptr };
};
#pragma once
#include "ICommand.h"
/* 具體命令類 */
class ConcreteCmd :public ICommand
{
public:
ConcreteCmd(CReceiver* pReceiver) :ICommand(pReceiver) {}
virtual void exec() override//具體命令執行介面:呼叫接受者對應的動作介面
{
m_pReceiver->action();
}
};
#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 };
};