1、特点
命令模式是最简单和优雅的模式之一,命令模式中的命令(command)指的是一个执行某些特定事情的指令。命令模式最常见的应用场景是:有时候需要向某些对象发送请求,但是并不知道请求的接收者是谁,也不知道被请求的操作是什么。此时希望用一种松耦合的方式来设计程序,使得请求发送者和请求接收者能够消除彼此之间的耦合关系。
2、demo
菜单程序
var bindClick = function(button, func) {
button.onclick = func;
};
var MenuBar = {
refresh: function() {
console.log('刷新菜单界面');
}
};
var SubMenu = {
add: function() {
console.log('增加子菜单');
},
del: function() {
console.log('删除子菜单');
}
};
bindClick(button1, MenuBar.refresh);
bindClick(button2, SubMenu.add);
bindClick(button3, SubMenu.del);
小球在平面上的移动
<html>
<body>
<p>是让页面上的小球移动到水平方向的某个位置。现在页面中有一个input 文本框和一个button 按钮,文本框中可以输入一些数字,表示小球移动后的水平位置,小球在用户点击按钮后立刻开始移动</p>
<div id="ball" style="position:absolute;background:#000;width:50px;height:50px"></div>
输入小球移动后的位置:<input id="pos" />
<button id="moveBtn">开始移动</button>
<button id="cancelBtn">cancel</cancel> <!--增加取消按钮-->
</body>
<script>
//设计模式的主题总是把不变的事物和变化的事物分离开来。
var ball = document.getElementById('ball');
var pos = document.getElementById('pos');
var moveBtn = document.getElementById('moveBtn');
var cancelBtn = document.getElementById('cancelBtn');
var MoveCommand = function(receiver, pos) {
this.receiver = receiver;
this.pos = pos;
this.oldPos = null;
};
MoveCommand.prototype.execute = function() {
this.receiver.start('left', this.pos, 1000, 'strongEaseOut');
this.oldPos = this.receiver.dom.getBoundingClientRect()[this.receiver.propertyName];
// 记录小球开始移动前的位置
};
MoveCommand.prototype.undo = function() {
this.receiver.start('left', this.oldPos, 1000, 'strongEaseOut');
// 回到小球移动前记录的位置
};
var moveCommand;
moveBtn.onclick = function() {
var animate = new Animate(ball);
moveCommand = new MoveCommand(animate, pos.value);
moveCommand.execute();
};
cancelBtn.onclick = function() {
moveCommand.undo(); // 撤销命令
};
</script>
</html>
参考文献:参考文献:《JavaScript设计模式与开发实践》