每天一個設計模式之命令模式

每天一個設計模式之命令模式

0. 示例代碼

  • 此節全部代碼 (https://godbmw.com/passages/2018-11-25-command-pattern/)

1. 什麼是“命令模式”

命令模式是一種數據驅動的設計模式,它屬於行為型模式。

  1. 請求以命令的形式包裹在對象中,並傳給調用對象。
  2. 調用對象尋找可以處理該命令的合適的對象,並把該命令傳給相應的對象。
  3. 該對象執行命令。

在這三步驟中,分別有 3 個不同的主體:發送者、傳遞者和執行者。在實現過程中,需要特別關注。

2. 應用場景

有時候需要向某些對象發送請求,但是又不知道請求的接受者是誰,更不知道被請求的操作是什麼。此時,命令模式就是以一種松耦合的方式來設計程序

3. 代碼實現

3.1 python3 實現

命令對象將動作的接收者設置在屬性中,並且對外暴露了execute接口(按照習慣約定)。

在其他類設置命令並且執行命令的時候,只需要按照約定調用Command對象的execute()即可。到底是誰接受命令,並且怎麼執行命令,都交給Command對象來處理!

__author__ = 'godbmw.com'
# 接受到命令,執行具體操作
class Receiver(object):
def action(self):
print("按鈕按下,執行操作")
# 命令對象
class Command:
def __init__(self, receiver):
self.receiver = receiver
def execute(self):
self.receiver.action()
# 具體業務類
class Button:
def __init__(self):
self.command = None
# 設置命令對戲那個
def set_command(self, command):
self.command = command
# 按下按鈕,交給命令對象調用相關函數
def down(self):
if not self.command:
return
self.command.execute()

if __name__ == "__main__":
receiver = Receiver()
command = Command(receiver)
button = Button()
button.set_command(command)
button.down()

3.2 ES6 實現

setCommand方法為按鈕指定了命令對象,命令對象為調用者(按鈕)找到了接收者(MenuBar),並且執行了相關操作。而按鈕本身並不需要關心接收者和接受操作

// 接受到命令,執行相關操作
const MenuBar = {
refresh() {
console.log("刷新菜單頁面");
}
};
// 命令對象,execute方法就是執行相關命令
const RefreshMenuBarCommand = receiver => {
return {
execute() {
receiver.refresh();
}
};
};
// 為按鈕對象指定對應的 對象
const setCommand = (button, command) => {
button.onclick = () => {
command.execute();
};
};
let refreshMenuBarCommand = RefreshMenuBarCommand(MenuBar);
let button = document.querySelector("button");
setCommand(button, refreshMenuBarCommand);

下面是同級目錄的 html 代碼,在谷歌瀏覽器中打開創建的index.html,並且打開控制檯,即可看到效果。







<title>命令模式/<title>


<button>按鈕/<button>



4. 參考

  • 《JavaScript 設計模式和開發實踐》
  • 如何實現命令模式


分享到:


相關文章: