1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
| interface Command { execute() : void; undo() : void; }
class ConcreteCommandOn implements Command { private receiver : Receiver; constructor(receiver : Receiver) { this.receiver = receiver; } public execute() : void { this.receiver.actionOn(); } public undo() : void { this.receiver.actionOff(); } }
class ConcreteCommandOff implements Command { private receiver : Receiver; constructor(receiver : Receiver) { this.receiver = receiver; } public execute() : void { this.receiver.actionOff(); } public undo() : void { this.receiver.actionOn(); } }
class NoCommand implements Command { public execute() : void {} public undo() : void {} } class Receiver { public actionOn() : void { console.log('我是命令接收者,开启了某动作'); } public actionOff() : void { console.log('我是命令接收者,关闭了某动作'); } } class Invoker { private onCommands : Array<Command>; private offCommands : Array<Command>; private undoCommand : Command; private slotNum : number = 7; constructor() { this.undoCommand = new NoCommand(); this.onCommands = []; this.offCommands = []; for (let i = 0; i < this.slotNum; i++) { this.onCommands[i] = new NoCommand(); this.offCommands[i] = new NoCommand(); } } public setCommand(index : number, onCommand : Command, offCommand : Command) : void { this.onCommands[index] = onCommand; this.offCommands[index] = offCommand; } public on (index : number) : void { this.onCommands[index].execute(); this.undoCommand = this.onCommands[index]; } public off (index : number) : void { this.offCommands[index].execute(); this.undoCommand = this.offCommands[index]; } public undo () : void { this.undoCommand.undo(); } } function main() { const receiver : Receiver = new Receiver(); const commandOn : Command = new ConcreteCommandOn(receiver); const commandOff : Command = new ConcreteCommandOff(receiver); const invoker : Invoker = new Invoker(); invoker.setCommand(0, commandOn, commandOff);
invoker.on(0); invoker.off(0); invoker.undo(); } main();
|