Can someone help me understand how can the Command Pattern in Java or C# enables "undo" functionality in application design? Any explanation would be appreciated.
Asked
Active
Viewed 428 times
3
-
@shmosel *maybe* the deeper duplicate works for this but I think this question isn't really getting at either. – BradleyDotNET Dec 07 '16 at 23:25
-
@BradleyDotNET What do you think it's getting at? – shmosel Dec 07 '16 at 23:26
-
@shmosel Why a command pattern makes Undo possible, not what the best option is for Undo (the answer to the nested duplicate touches on this, but not all that well IMO). – BradleyDotNET Dec 07 '16 at 23:27
1 Answers
2
Undo functionality requires that you store the last n-number of user actions. Typically a user action simply results in a function call, so its very hard to store it. Its even harder to store it in a way that is undoable.
By abstracting a user action into an object, you can easily put a set of these objects into a data structure (typically Stack
) and if you put an Undo
method onto the object you just go through the structure and call the Undo
method as the user requests the undo operation.
Since Command is already set up to encapsulate an operation (user or otherwise) it is an excellent starting point for building undo functionality.

BradleyDotNET
- 60,462
- 10
- 96
- 117