JS命令模式例子之菜单程序
命令模式的应用场景:
有时候需要向某些对象发送请求,但是并不知道请求的接收者是谁,也不知道被请求的操作是什么,此时希望用一种松耦合的方式来设计软件,使得请求发送者和请求接收者能够消除彼此之间的耦合关系。
html代码:
<!DOCTYPEhtml>
<html>
<head>
<metacharset="utf-8"/>
<title>js:命令模式</title>
<scripttype="text/javascript"src="command.js"></script>
</head>
<styletype="text/css">
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:2pxsolid#6B78BF;
}
</style>
<body>
<buttonid="button1">刷新</button>
<buttonid="button2">新增</button>
<buttonid="button3">删除</button>
<br/>
<textareaid="textarea">
这是预设的内容
</textarea>
</body>
</html>
js代码:
//在页面中使用例:setCommand(button1,refreshMenuBarCommand);来发送命令
//setCommand函数负责往按钮上面安装命令,预留好安装命令的接口
varsetCommand=function(button,command){
button.onclick=function(){
command.execute();
}
}
//编写点击按钮之后的具体行为:刷新菜单界面、增加子菜单和删除子菜单
varMenuBar={
refresh:function(){
varcur_date=newDate();
document.getElementById("textarea").value+=cur_date.toLocaleString()+"刷新菜单目录\r";
}
}
varSubMenu={
add:function(){
varcur_date=newDate();
document.getElementById("textarea").value+=cur_date.toLocaleString()+"新增菜单目录\r";
},
del:function(){
varcur_date=newDate();
document.getElementById("textarea").value+=cur_date.toLocaleString()+"删除子菜单\r";
}
}
//封装行为在命令类中
varRefreshMenuBarCommand=function(receiver){
this.receiver=receiver;
}
RefreshMenuBarCommand.prototype.execute=function(){
this.receiver.refresh();
}
varAddSubMenuCommand=function(receiver){
this.receiver=receiver;
}
AddSubMenuCommand.prototype.execute=function(){
this.receiver.add();
}
varDelSubMenuCommand=function(receiver){
this.receiver=receiver
}
DelSubMenuCommand.prototype.execute=function(){
this.receiver.del();
}
//命令接收者传入到command对象
varrefreshMenuBarCommand=newRefreshMenuBarCommand(MenuBar);
varaddSubMenuCommand=newAddSubMenuCommand(SubMenu);
vardelSubMenuCommand=newDelSubMenuCommand(SubMenu);
window.onload=function(){
//把command对象安装到button上面
varbutton1=document.getElementById("button1");
varbutton2=document.getElementById("button2");
varbutton3=document.getElementById("button3");
setCommand(button1,refreshMenuBarCommand);
setCommand(button2,addSubMenuCommand);
setCommand(button3,delSubMenuCommand);
}
总结:
从书上抄代码练习的过程中出了很多错误,最严重的莫过于“receiver”这个单词写错了导致很多天都再没看这个练习,出错的过程让我能够重新审视代码的内容,逐行进行理解与调试。虽然仍然不很理解命令模式,但是通过这部分的内容和对mySQL的学习,心里隐隐的留下了关于命令模式的影子。
参考:
《JavaScript设计模式与开发实践》第9章9.2节
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。