命令模式是一种数据驱动的设计模式,它属于行为型模式。
在这三步骤中,分别有 3 个不同的主体:发送者、传递者和执行者。在实现过程中,需要特别关注。
有时候需要向某些对象发送请求,但是又不知道请求的接受者是谁,更不知道被请求的操作是什么。此时,命令模式就是以一种松耦合的方式来设计程序。
命令对象将动作的接收者设置在属性中,并且对外暴露了execute
接口(按照习惯约定)。
在其他类设置命令并且执行命令的时候,只需要按照约定调用Command
对象的execute()
即可。到底是谁接受命令,并且怎么执行命令,都交给Command
对象来处理!
__author__ = 'godbmw.com'# 接受到命令,执行具体操作class Receiver(object):def action(self):print("按钮按下,执行操作")# 命令对象class Command:def __init__(self, receiver):self.receiver = receiverdef 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:returnself.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>