Implementing the command pattern
Asked Answered
A

2

14

I am in the design process of an application, and I would like to use the command pattern for undo/redo purposes. I did some research into the command pattern but the only thing I don't get is: Should a command have the undo and redo methods, or should I make two separate commands, one for undo and one for redo, and call those from the main command itself?

Artificial answered 6/2, 2010 at 21:47 Comment(0)
H
11

The command object itself should implement the undo / redo functionality.

The commands are generally pushed and popped from a stack maintained by a command manager to implement multi level undo. When commands are executed they are pushed onto the stack and when they are undone they are popped from the stack.

The memento pattern would be used in conjunction with the command pattern, it is not a replacement to the usage of the command pattern. It would be used to maintain the state required for the undo operation.

Happily answered 6/2, 2010 at 21:49 Comment(2)
I'd add that a better solution isn't just a simple stack. Instead, you want a list and a reference to the current item. Undoing walks the reference back, and redoing walks it forward. Using a stack doesn't let you redo.Snippet
I've used 2 stacks, undo and redo stack. If you undo an action, it pops from the undo stack and pushes onto the redo stack. Adding a new action is pushing a new one onto the undo stack and clearing the redo stack.Apocrypha
E
2

You might also want to consider the memento pattern for this, we use it and it works brilliant for undo.

Elspet answered 6/2, 2010 at 23:8 Comment(5)
Will the memento pattern be less time consuming to implement then the command pattern when i only want it for undoing ?Artificial
@Artificial The memento pattern would be used in conjunction with the command pattern, it is not a replacement to the usage of the command pattern.Happily
So the memento would hold the undo and redo stacks, And the stacks will contain the commands am i right ?Artificial
@Artificial The memento would hold the objects previous state so that it could be undone.Happily
The memento pattern can eat a lot of memory if your objects are large. Using the command pattern basically means storing just the difference between the object's previous and current state, where a memento stores the entire state.Snippet

© 2022 - 2024 — McMap. All rights reserved.