如题

解决方案 »

  1.   

    当然可以,参见:Command模式-命令模式
      

  2.   

    简单写个参考的:
    <style type="text/css">
    div{border:3px solid black;padding:10px;}
    </style><div id="x">初始值</div><script type="text/javascript">
    //要应用command模式的对象
    var box = function(dbox,svalue){
    this.value = svalue;
    this.dbox = dbox;
    this.restart = function(){//约定一个回到初始状态的方法
    this.value = svalue;
    this.dbox.innerHTML = svalue;
    };
    };
    box.prototype = {
    setValue:function(svalue){
    this.value = svalue;
    this.dbox.innerHTML = svalue;
    }
    };
    //command对象
    var command = function(receiver){
    this.receiver = receiver;
    this.log = [];
    this.un_re_do = -1;
    };
    command.prototype = {
    query:function(cmd){
    if(!cmd||cmd.constructor!=Function){return;}
    var args = Array.prototype.slice.call(arguments,0);
    var idx = this.un_re_do+1,ll = this.log.length;
    if(ll){this.log.splice(idx,ll-idx);}
    this.log.push(args);
    this.un_re_do++;
    this.exec.apply(this,args);
    },
    exec:function(){
    var args = Array.prototype.slice.call(arguments,0);
    if(!args.length){return;}
    var cmd = args.shift();
    if(cmd.constructor!=Function){return;}
    cmd.apply(this.receiver,args);
    },
    undo:function(){
    var idx = (this.un_re_do>=0)?--this.un_re_do:-1;
    this.unredo(idx);
    },
    redo:function(){
    var idx = (this.un_re_do<this.log.length-1)?++this.un_re_do:this.un_re_do;
    this.unredo(idx);
    },
    unredo:function(idx){
    if(idx>=0){
    var cmd_step = this.log[idx];
    this.exec.apply(this,cmd_step);
    }else{
    this.receiver.restart();
    }
    }
    };var hellobox = new box(document.getElementById('x'),'初始值');
    var boxCommand = new command(hellobox);window.setTimeout(function(){boxCommand.query(hellobox.setValue,'第一次修改值!');},1000);
    window.setTimeout(function(){boxCommand.undo();},2000);
    window.setTimeout(function(){boxCommand.query(hellobox.setValue,'第二次修改值!');},3000);
    window.setTimeout(function(){boxCommand.undo();},4000);
    window.setTimeout(function(){boxCommand.redo();},5000);
    window.setTimeout(function(){boxCommand.query(hellobox.setValue,'第三次修改值!');},6000);
    window.setTimeout(function(){boxCommand.query(hellobox.setValue,'第四次修改值!');},7000);
    window.setTimeout(function(){boxCommand.undo();},8000);
    window.setTimeout(function(){boxCommand.undo();},9000);
    window.setTimeout(function(){boxCommand.undo();},10000);
    </script>