做者按:《天天一個設計模式》旨在初步領會設計模式的精髓,目前採用
javascript
和python
兩種語言實現。誠然,每種設計模式都有多種實現方式,但此小冊只記錄最直截了當的實現方式 :)javascript
原文地址是:《天天一個設計模式之命令模式》html
歡迎關注我的技術博客:godbmw.com。每週 1 篇原創技術分享!開源教程(webpack、設計模式)、面試刷題(偏前端)、知識整理(每週零碎),歡迎長期關注!前端
若是您也想進行知識整理 + 搭建功能完善/設計簡約/快速啓動的我的博客,請直接戳theme-bmwjava
命令模式是一種數據驅動的設計模式,它屬於行爲型模式。python
在這三步驟中,分別有 3 個不一樣的主體:發送者、傳遞者和執行者。在實現過程當中,須要特別關注。webpack
有時候須要向某些對象發送請求,可是又不知道請求的接受者是誰,更不知道被請求的操做是什麼。此時,命令模式就是以一種鬆耦合的方式來設計程序。git
命令對象將動做的接收者設置在屬性中,而且對外暴露了execute
接口(按照習慣約定)。github
在其餘類設置命令而且執行命令的時候,只須要按照約定調用Command
對象的execute()
便可。究竟是誰接受命令,而且怎麼執行命令,都交給Command
對象來處理!web
__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()
複製代碼
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
,而且打開控制檯,便可看到效果。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>命令模式</title>
</head>
<body>
<button>按鈕</button>
<script src="./main.js"></script>
</body>
</html>
複製代碼