function Command(receiver) { this.receiver = receiver; } Command.prototype.execute = function() { // 执行命令 this.receiver.executeCommand(); }; Command.prototype.undo = function() { // 撤销命令 this.receiver.undoCommand(); }; function Receiver() { // 接收者对象 } Receiver.prototype.executeCommand = function() { // 执行命令的具体逻辑 }; Receiver.prototype.undoCommand = function() { // 撤销命令的具体逻辑 }; function Invoker() { this.commands = []; } Invoker.prototype.addCommand = function(command) { this.commands.push(command); }; Invoker.prototype.executeCommands = function() { for (var i = 0; i < this.commands.length; i++) { this.commands[i].execute(); } }; Invoker.prototype.undoCommands = function() { for (var i = this.commands.length - 1; i >= 0; i--) { this.commands[i].undo(); } }; var receiver = new Receiver(); var command1 = new Command(receiver); var command2 = new Command(receiver); var invoker = new Invoker(); invoker.addCommand(command1); invoker.addCommand(command2); invoker.executeCommands(); // 执行命令 invoker.undoCommands(); // 撤销命令
本文为翻滚的胖子原创文章,转载无需和我联系,但请注明来自猿教程iskeys.com