美文网首页
设计模式-【命令模式】

设计模式-【命令模式】

作者: 伏波Rinnsio1xy | 来源:发表于2018-09-28 09:54 被阅读8次

二、实例代码:

function makeMoveUnitCommand(unit, x, y) {
    var xBefore, yBefore;
    return {
        execute: function() {
            xBefore = unit.x();
            yBefore = unit.y();
            console.log("x y before", xBefore, yBefore)
            unit.moveTo(x, y);
        },
        undo: function() {
            unit.moveTo(xBefore, yBefore);
        }
    };
}

function Unit(){
    this.m_x = 0
    this.m_y = 0
}

Unit.prototype.x = function(){
    return this.m_x
}

Unit.prototype.y = function(){
    return this.m_y
}

Unit.prototype.moveTo = function(x, y){
    this.m_x = x
    this.m_y = y
    console.log("move to x, y", x, y)
};

var unit = new Unit()

var cmd = new makeMoveUnitCommand(unit, 10, 10)
cmd.execute()

var cmd = new makeMoveUnitCommand(unit, 20, 10)
cmd.execute()
cmd.undo()

相关文章

网友评论

      本文标题:设计模式-【命令模式】

      本文链接:https://www.haomeiwen.com/subject/wyuuoftx.html