The power and simplicity of the Command pattern
2 min read
2 min read
Never thought of how to implement an "undo" function? Not that easy, huh? People in our architecture class today came up with quite creative solutions: two separate stacks storing operations, versioning of the object to go back etc... All quite complex. Well, I've thought about that already about a year ago, so it was quite easy for me and there you actually see how simple such a task becomes if you know the right pattern (I'll come to it immediately).
The key is actually to encapsulate the operation and the object the operation acts on. If you encapsulate that within an object you're already pretty much done. Every time you perform an operation you create such an object encapsulating that operation.public class BoldCommand implements ICommand{I guess this should look now pretty obvious to you. Of course this is just a simple code for demonstrating the idea. You need some more sophisticated structures that take care of these command objects. For the undo/redo you'd probably have some list that tracks all of these objects, removes old ones etc...
private Word aWord;
public BoldCommand(Word aWord){
this.aWord = aWord;
}
public void execute(){
//call some appropriate object that knows how to perform
//the action, i.e.
aWord.setBold(true);
}
public void undo(){
//undoing is easy since we know here what we did previously and
//we have the reference to the object we acted upon
aWord.setBold(false);
}
public void redo(){
execute();
}
}