// 定义撤销和重做命令的基类
class Command {
  execute() {}
  undo() {}
  redo() {}
}
// 示例命令类
class ChangeTextCommand extends Command {
  constructor(receiver, newText) {
    super()
    this.receiver = receiver
    this.newText = newText
    this.oldText = receiver.text
  }
  execute() {
    this.receiver.text = this.newText
  }
  undo() {
    this.receiver.text = this.oldText
  }
  redo() {
    this.execute()
  }
}
// 接收者对象
class TextEditor {
  constructor() {
    this.text = ''
  }
}
// 客户端代码
class Client {
  constructor() {
    this.editor = new TextEditor()
    this.history = []
    this.currentIndex = -1
  }
  executeCommand(command) {
    command.execute()
    this.currentIndex++
    this.history = this.history.slice(0, this.currentIndex)
    this.history.splice(this.currentIndex, 1, command)
  }
  undo() {
    if (this.currentIndex >= 0) {
      const command = this.history[this.currentIndex]
      command.undo()
      this.currentIndex--
    }
  }
  redo() {
    if (this.currentIndex < this.history.length - 1) {
      this.currentIndex++
      const command = this.history[this.currentIndex]
      command.redo()
    }
  }
}
// 示例用法
const client = new Client()
const command1 = new ChangeTextCommand(client.editor, 'Hello')
client.executeCommand(command1)
console.log(client.editor.text) // 输出: 'Hello'
const command2 = new ChangeTextCommand(client.editor, 'World')
client.executeCommand(command2)
console.log(client.editor.text) // 输出: 'World'
client.undo()
console.log(client.editor.text) // 输出: 'Hello'
client.redo()
console.log(client.editor.text) // 输出: 'World'