《大話設計模式》C++實現:23 命令模式(三)抽象總結

2020-10-05 19:00:21

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 };
};