命令模式的应用场景:

        有时候需要向某些对象发送请求,但是并不知道请求的接收者是谁,也不知道被请求的操作是什么,此时希望用一种松耦合的方式来设计软件,使得请求发送者和请求接收者能够消除彼此之间的耦合关系。

html代码:

<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8" />
 <title>js:命令模式</title>
 <script type="text/javascript" src="/UploadFiles/2021-04-02/command.js">

js代码:

// 在页面中使用例:setCommand( button1, refreshMenuBarCommand );来发送命令


// setCommand 函数负责往按钮上面安装命令,预留好安装命令的接口
var setCommand = function( button , command ){
 button.onclick = function(){
 command.execute();
 }
}

// 编写点击按钮之后的具体行为:刷新菜单界面、增加子菜单和删除子菜单
var MenuBar = {
 refresh: function(){
 var cur_date = new Date();
 document.getElementById("textarea").value+=cur_date.toLocaleString()+" 刷新菜单目录\r";
 }
}
var SubMenu = {
 add: function(){
 var cur_date = new Date();
 document.getElementById("textarea").value+=cur_date.toLocaleString()+" 新增菜单目录\r";
 },
 del: function(){
 var cur_date = new Date();
 document.getElementById("textarea").value+=cur_date.toLocaleString()+" 删除子菜单\r";
 }
}

//封装行为在命令类中
var RefreshMenuBarCommand = function( receiver ){
 this.receiver = receiver;

}
RefreshMenuBarCommand.prototype.execute = function(){
 this.receiver.refresh();
}
var AddSubMenuCommand = function( receiver ){
 this.receiver = receiver;
}
AddSubMenuCommand.prototype.execute = function(){
 this.receiver.add();
}
var DelSubMenuCommand = function( receiver ){
 this.receiver =receiver
}
DelSubMenuCommand.prototype.execute = function(){
 this.receiver.del();
}

//命令接收者传入到 command 对象
var refreshMenuBarCommand = new RefreshMenuBarCommand( MenuBar );
var addSubMenuCommand = new AddSubMenuCommand( SubMenu );
var delSubMenuCommand = new DelSubMenuCommand( SubMenu );

window.onload = function(){
 //把 command 对象安装到 button 上面
 var button1 = document.getElementById("button1");
 var button2 = document.getElementById("button2");
 var button3 = document.getElementById("button3");
 setCommand( button1, refreshMenuBarCommand );
 setCommand( button2, addSubMenuCommand );
 setCommand( button3, delSubMenuCommand );
}

总结:

从书上抄代码练习的过程中出了很多错误,最严重的莫过于“receiver”这个单词写错了导致很多天都再没看这个练习,出错的过程让我能够重新审视代码的内容,逐行进行理解与调试。虽然仍然不很理解命令模式,但是通过这部分的内容和对mySQL的学习,心里隐隐的留下了关于命令模式的影子。

参考:

《JavaScript设计模式与开发实践》第9章9.2节

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com