Search code examples
javadesign-patternsundo-redo

Implementing undo in Java for state changes


I am starting to implementing the command pattern in the hope to get a useful solution to my problem of providing an undo operation. Now I am facing a certain issue:

Implementing undo when operations are involved are rather easy: when I've added 5 to a number then I subtract 5. When I've added an object to a list, then I remove it, and so on. But what if I have a total state and not something like a list?

An example: I model information about a thread in a class:

public class ThreadInfo implements Comparable<ThreadInfo> {

    final int id;
    String name;
    int priority;
    String state;
    int waitCount;
    // ...
}

Certain information does not change, for instance the id. Undoing the waitCount is easy as described above, just subtract. But what about priority or state? It is not clear how to undo these information.

The only idea I came up with: when initializing the command object, preserve the old state in it's object: by passing the relevant data into the constructor:

public MyCommand(int priority, String state) {
   previousPriority = priority;
   previousState = state;
}

Or would it be better to let ThreadInfo have a list of states and priorities with being the first elements the current?


Solution

  • Just hold old state in command. for example

     class ChangeFoo {
        ChangeFoo (Bar bar, foo newFoo){}
        void execute(){
            oldFoo = bar.getFoo();
            bar.setFoo(newFoo);
        }
        void undo(){
            bar.setFoo(oldFoo);
        }
     }