設計模式 命令模式

2021-10-08 14:17:23 字數 1520 閱讀 9207

將請求封裝成物件,以便使用不同的請求、日誌、佇列等來引數化其他物件。命令模式也支援撤銷操作。

我們拿最近很火的智慧型家居來做舉例

小公尺的智慧型家居描繪的應用場景之一是智慧型音箱可以控制其他家用電器工作

先定義抽象的command類

public

inte***ce

command

當前有兩個家電,燈和電視

public

class

light

public

void

turnofflight()

}public

class

tvpublic

void

closetv()

}

分別實現對燈的開關請求

public

class

lightoncommand

implements

command

@override

public

void

execute()

}public

class

lightoffcommand

implements

command

@override

public

void

execute()

}

還有電視的開關請求

public

class

opentvcommand

implements

command

@override

public

void

execute()

}public

class

closetvcommand

implements

command

@override

public

void

execute()

}

作為invoker的智慧型音箱

public

class

speakers

public

void

cancelcommand

(command command)

public

void

execute()

commands.

clear();}}

使用

public

class

demo

}

命令模式把請求乙個操作的物件與知道怎麼執行乙個操作的物件分隔開,實現了解耦。

設計模式 命令設計模式

一句話總結 命令設計模式的實質是將命令定義,命令的執行分離開,從而提公升了系統的解藕性 結構 命令的抽象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...