1.命令模式
命令模式中的命令是指的一個執(zhí)行某些特定事情的指令,主要應用于向某些對象發(fā)送請求,但是不知道請求的接收者是誰,也不知道被請求的操作是什么,可以用一種松散耦合的方式來設計軟件,使發(fā)送者與接收者能消除彼此之間的耦合關系。
另外,命令模式還支持撤銷、排隊等操作。
2.撤銷命令
命令模式可以封裝運算塊,命令對象不僅可以用執(zhí)行方法,還可以添加撤銷方法。
這里可以利用策略模式建立的一個動畫庫,實現(xiàn)動畫的開啟和返回操作。
//將動畫對象封裝成命令對象,為了方便地添加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');
}