二、实例代码:
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()
网友评论