css部分:
<style type="text/css">
button{
margin:5px;
border:0;
width:70px;
line-height: 40px;
background:#12c7fe;
color:#fff;
font-size:18px;
cursor: pointer;
}
#textarea{
margin: 5px;
width:400px;
height:200px;
color:#0066cc;
font-size:20px;
border: 2px solid #7274A7 ;
}
</style>
html:
<div style="text-align: center;width: 390px;">
<button id="btn1">F5</button>
<button id="btn2">新增</button>
<button id="btn3">删除</button>
</div>
<br/>
<textarea id="textarea">
write something...
</textarea>
js:命令模式实现菜单
<script>
var setCommand = function(btn,command){
btn.onclick = function () {
command.execute();
}
}
var supMenu={
refresh:function(){
document.getElementById("textarea").value+="刷新界面";
}
}
var subMenu={
add:function(){
document.getElementById("textarea").value+="添加...";
},
del:function () {
document.getElementById("textarea").value+="删除...";
}
}
var refreshCommand = function (receiver) {
this.receiver = receiver;
}
refreshCommand.prototype.execute = function () {
this.receiver.refresh();
}
var addCommand = function (receiver) {
this.receiver = receiver;
}
addCommand.prototype.execute = function () {
this.receiver.add();
}
var delCommand = function (receiver) {
this.receiver = receiver;
}
delCommand.prototype.execute = function () {
this.receiver.del();
}
var btn1 = document.getElementById("btn1");
setCommand(btn1,new refreshCommand(supMenu));
var btn2 = document.getElementById("btn2");
setCommand(btn2,new addCommand(subMenu));
var btn3 = document.getElementById("btn3");
setCommand(btn3,new delCommand(subMenu));
</script>
setCommand(btn,command)这个就是命令模式中建立关系的代码;只需要知道按钮和命令就行了;点击按钮,就执行command.execute();
var addCommand = function (receiver) { this.receiver = receiver; } addCommand.prototype.execute = function () { this.receiver.add(); }
是一块;prototype 这个属性是函数特有的属性 ,而且是函数的原型对象。 对原型对象增加的属性及其方法,new实例化 之后的对象都能继承。
所以说setCommand里的command是:new addCommand(subMenu); 记得要new对象实例化
其实一直都不太了解设计模式到底该怎么应用;通过这个例子或许可以拓展一下将其中所实现的方法__>(prototype.execute=function(){})转换为别的比如说传值跳转页面什么的;而setCommand(btn,command)这个方法会让代码更加的易懂。