設計模式(二十二)——行爲變化模式-Command_命令模式

對象模式所屬類別簡介

行爲變化模式分爲Command、visitor。
在組件的構建構成中,組件行爲的變化經常導致組件本身劇烈的變化。行爲變化模式將組件的行爲和組件本身進行解耦,從而支持組件行爲的變化,實現兩者之間的鬆耦合。

當前模式簡介動機

將一組行爲抽象爲對象,實現行爲請求者和行爲實現者進行解耦合。

需求

有兩個指令,設置爲一個總控制,總控制調用後調用兩個指令對象。

設計一

需求更改

設計一更改版本

違反原則

設計二

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;

class ICommand 
{
public:
	virtual void execute()=0;
};

class Command1 : public ICommand
{
	string m_arg;
public:
	Command1(const string &str):m_arg(str){}
	virtual void execute(){ std::cout << m_arg << std::endl;}
};
class Command2 : public ICommand
{
	string m_arg;
public:
	Command2(const string &str):m_arg(str){}
	virtual void execute(){ std::cout << m_arg << std::endl;}
};

class Commander:public ICommand
{
	vector<ICommand*> m_argVec;
public:
	void addCmd(ICommand &cmd){m_argVec.push_back(&cmd);}
	virtual void execute()
	{
		for (auto i:m_argVec)
		{
			(*i).execute();
		}

	}
};

int main()
{
	Command1 cmd1("aaaaaaaaaa");
	Command2 cmd2("bbbbbbbbbb");
	Commander cmd;
	cmd.addCmd(cmd1);
	cmd.addCmd(cmd2);
	cmd.execute();
	return 0;
}

設計二更改版本

設計二比設計一區別

模式定義

將一個請求(行爲)封裝爲一個對象,從而使你可用不同的請求對客戶進行參數化;隊請求排隊或記錄請求日誌,以及支持可撤銷的操作。

模式結構

在這裏插入圖片描述

要點總結

行爲抽象爲對象,實現鬆耦合。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章