So far, I have not come up with a beautiful solution for implementing UNDO / REDO commands in Java. To work with the command stack, I want to use the “Team” pattern, i.e. you need to implement the "Team" pattern + a couple of classes of commands, and so that from the client class, when calling a particular command, the called commands are added to the history stack, and so that you can roll back the executed commands using the UNDO / REDO command.

More specifically, the problem is that I still don’t understand where it is better to implement the stack of executed commands, while I see 3 options, but I would like to hear the opinions of those who implemented UNDO / REDO in Java.

So my options are: 1. In the client class 2. In the Invoker class (Caller class) 3. In the Receiver class

  • 2
    Can add a client to the class for now, and then move it to another place if you don’t like it? It seems to me that for the beginning it does not matter where to put them, you can at least in a separate class, but rather concentrate on writing classes of commands, for example. - diraria September
  • @diraria, let's say there are two classes of commands, and when the command is executed, they are added to the stack on the client. Then how to roll back the changes that the team made? If you simply delete the command object from the stack, then this seems to be not enough, you have to either re-launch the stack with the commands and overwrite the result, or somehow, I don’t know yet how. - zuvladimir
  • one
    I see two options: 1. If the rollback operation is simply implemented for the commands, then add the undo method to the command class (to the already existing do method), when you cancel the command, you will call this method. 2. Otherwise, you can take a snapshot every few actions (depending on the size of the snapshots and the average time for using the commands it can be 10, 100 or 1000), take snapshots too, when you cancel the command to load the last snapshot and apply all of the following to it teams followed him except the last - diraria
  • one
    I also want to note that if all the commands are stored on the stack and if you cancel the command, you will delete the last element from the stack, then the redo method will not be able to receive the command that needs to be reapplied. You can save remote commands to another stack, or instead of a stack, use a stack that supports indexing and store the index of the current command. - diraria
  • one

0