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 prior开发者_开发技巧ities with being the first elements the current?
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);
}
}
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.
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.
It's better to have a Backup of the old object in side your comand method. I already used this type of approach .
精彩评论