命令模式的应用场景:
有时候需要向某些对象发送请求,但是并不知道请求的接收者是谁,也不知道被请求的操作是什么,此时希望用一种松耦合的方式来设计软件,使得请求发送者和请求接收者能够消除彼此之间的耦合关系。
html代码:
js:命令模式 button{ margin: 5px; border: 0; width: 70px; height: 35px; background: #6B78BF; color: white; font-size: 14px; font-family: "微软雅黑"; cursor: pointer; } #textarea{ margin: 5px; width: 400px; height: 200px; resize: none; color: #666; font-size: 14px; border: 2px solid #6B78BF; }
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节
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



