做者按:《天天一个设计模式》旨在初步领会设计模式的精髓,目前采用
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>
复制代码