1.命令模式
命令模式中的命令是指的一个执行某些特定事情的指令,主要应用于向某些对象发送请求,但是不知道请求的接收者是谁,也不知道被请求的操作是什么,可以用一种松散耦合的方式来设计软件,使发送者与接收者能消除彼此之间的耦合关系。
另外,命令模式还支持撤销、排队等操作。
2.撤销命令
命令模式可以封装运算块,命令对象不仅可以用执行方法,还可以添加撤销方法。
这里可以利用策略模式建立的一个动画库,实现动画的开启和返回操作。
//将动画对象封装成命令对象,为了方便地添加undo的功能
function AnimationCommand(animation){
this.animation=animation;
this.oldPos=null;
this.oldStart=null;
}
AnimationCommand.prototype.execute=function(pos,duration){
this.oldPos=this.animation.dom.getBoundingClientRect().left;
this.oldStart=+new Date();
this.animation.start('left',pos,duration,'easeIn');
};
AnimationCommand.prototype.undo=function(){
var dur=+new Date()-this.oldStart;
this.animation.start('left',this.oldPos,dur,'easeIn');
}
网友评论