命令模式

将Command作为一个抽象类(或者接口),而非一个函数
支持统一的Execute和Undo
 
example
public abstract class Command { public virtual void Execute(GameActor actor); public virtual void Undo(GameActor actor); } public class JumpCommand: Command { public override void Execute (GameActor actor) { actor.jump(); } // Undo 略 }
实际处理
public class InputHandler : SingletonMono<InputHandler>{ public Command HandleInput() { if (isPressed(BUTTON_X)) return buttonX; if (isPressed(BUTTON_Y)) return buttonY; if (isPressed(BUTTON_A)) return buttonA; if (isPressed(BUTTON_B)) return buttonB; // 没有按下任何按键,就什么也不做 return NULL; } private Command buttonX; private Command buttonY; private Command buttonA; private Command buttonB; // Initialize } // Call Command* command = InputHandler.GetInstance().HandleInput(); if (command is not null) { command.Execute(actor); }
 
Undo操作的支持:需要记录「Previous State」
 
用闭包替代一个类:
function makeMoveUnitCommand(unit, x, y) { var xBefore, yBefore; return { execute: function() { xBefore = unit.x(); yBefore = unit.y(); unit.moveTo(x, y); }, undo: function() { unit.moveTo(xBefore, yBefore); } }; }