Undoing commands

While not directly related, one of the advantages of the Command design pattern is the ability to undo commands. What if we wanted to support such a functionality?

Undoing is usually very tricky, because it involves one of the following:

  • Returning to the previous state (impossible if there's more than one client, requires a lot of memory)
  • Computing deltas (tricky to implement)
  • Defining opposite operations (not always possible)

In our case, the opposite of the command move from (0,0) to (0, 20) would be move from wherever you're now to (0,0). This could be achieved by storing a pair of commands:

private val commands = mutableListOf<Pair<Command, Command>>()

You can also add pairs of commands:

fun appendMove(x: Int, y: Int) = apply {
val oppositeMove = /* If it's the first command, generate move to current location. Otherwise, get the previous command */
commands.add(moveGenerator(this, x, y) to oppositeMove)
}

Actually, computing the opposite move is quite complex, as we don't save the position of our soldier currently (it was something Dave should have implemented anyway), and we'll also have to deal with some edge cases.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.30.62