設計模式 命令模式

2021-09-08 21:43:33 字數 1972 閱讀 6969

命令模式(command)的目標是將乙個請求封裝成乙個物件,因此可以引數化多個客戶的不同請求,將請求排除,記錄請求日誌,並支援撤消操作。 結構圖如下:

其實現思想是將乙個請求封裝到乙個類中(command),再提供接收物件(receiver),最後command命令由invoker呼叫。 

以乙個電燈開關為例,命令的執行、不執行相對於開關的開啟、關閉操作,由開關發出命令,電燈接收命令,結構圖如下:

實現**:

// light.h

class

light  ;//

light.cpp

#include 

" stdafx.h

" #include 

" light.h

" #include 

<

iostream

>

using

namespace

std;

light::light()

light::

~ light()

void

light::turnon()

void

light::turnoff()

// command.h

class

command  ;//

command.cpp

#include 

" stdafx.h

" #include 

" command.h

" command::command()

command::

~ command()

// lightcommand.h

#include 

" command.h

" class

light;

class

lightcommand : 

public

command;//

lightcommand.cpp

#include 

" stdafx.h

" #include 

" lightcommand.h

" #include 

" light.h

" lightcommand::lightcommand(light

*  plight)

lightcommand::

~ lightcommand()

}void

lightcommand::execute()

void

lightcommand::unexecute()

// switch.h

class

command;

class

switch  ;//

switch.cpp

#include 

" stdafx.h

" #include 

" switch.h

" #include 

" command.h

" switch::switch(command

*  pcommand)

switch::

~ switch()

void

switch::open()

void

switch::close()

// main.cpp

#include 

" stdafx.h

" #include 

" switch.h

" #include 

" light.h

" #include 

" lightcommand.h

" int  main(

intargc, 

char

*  ar**)

最後輸出為:

電燈開啟了

電燈關閉了

設計模式 命令設計模式

一句話總結 命令設計模式的實質是將命令定義,命令的執行分離開,從而提公升了系統的解藕性 結構 命令的抽象command 命令的具體實現concretecommand 命令處理者抽象ireceiver 命令處理者的具體實現concretereceiver 命令的呼叫者invoker 客戶端client...

設計模式 命令模式

1 命令模式的角色組成 1 命令角色 command 生命執行操作的介面。介面或抽象類來實現。2 具體命令角色 concrete command 將乙個接收者物件繫結於乙個動作 呼叫接收者相應的操作,以實現命令角色宣告的執行操作的介面。3 客戶角色 client 建立乙個具體命令物件 並可以設定它的...

設計模式 命令模式

1 command.h ifndef command h define command h include include include using namespace std class chef 廚師,具體命令的執行者 class command 命令基類 class makemuttonco...