Konrad Reiche
Konrad Reiche

Reputation: 29483

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?

Upvotes: 3

Views: 3015

Answers (4)

David Tanzer
David Tanzer

Reputation: 2742

I would go for the first solution: MyCommand constructor which saves the state. It is simple and should work. For a more general undo/redo approach, have a look at the memento pattern. You can probably combine it with your command based approach.

Upvotes: 2

BOSS
BOSS

Reputation: 2951

It's better to have a Backup of the old object in side your comand method. I already used this type of approach .

Upvotes: 0

Stan Kurilin
Stan Kurilin

Reputation: 15792

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);
    }
 }

Upvotes: 5

Heisenbug
Heisenbug

Reputation: 39164

Java already have support for undo/redo operations. Have a look a this tutorial. You can extends AbstractUndoableEdit class to define the semantic of undo/redo operations on your objects.

Upvotes: 0

Related Questions