How to implement undo functionality?

In my application, I want to provide the user with a small undo functionality. The user does not have many actions that can be undone by the user. In particular, the actions:

  • Adding notes to an object
  • Object color
  • Flag objcet with string

Now I was thinking about how to implement this. At first I thought of the Action class, which is an abstract base class for three different actions that can be taken by the user. Each time the user takes these actions, a new corresponding instance of the subclass of this abstract class Action is created and inserted into the list containing all the actions.

Whenever the user wants to cancel something, the list is displayed to the user, and he can choose which action he wants to cancel.

Now I thought what should be stored in such an action object:

  • object state before action
  • the actual action that was performed (for example, a line added to the notes of the object)

I'm not sure if this is enough. I also thought of something like a chronological ordering, but this is necessary since the list can be kept chronologically correct.

Are there any other things I should consider?

+8
c # architecture system-design
source share
6 answers

Undo / redo is usually implemented with the Command Pattern . The Action class can be used as the basis for this, but you need to do the do and cancel actions on each command. Here is an example of this in practice. You should probably keep the commands executed on the stack, as this greatly simplifies the implementation and is much easier for the user.

+14
source share

You could do something simple:

 Stack<Action> undoStack = new Stack<Action>(); void ChangeColor(Color color) { var original = this.Object.Color; undoStack.Push(() => this.Object.Color = original); this.Object.Color = color; } 
+9
source share

you should implement the Command Template for each action you want to undo:

how to perform a cancel / redo operation without significant changes in the program

+5
source share

Everything seems to be correct, but I'd rather use a stack than a list. This will be useful in the aspect of chronological ordering.

+2
source share

For a correct and proven implementation of UNDO functions, the Command Pattern

+2
source share

It's hard to miss this Simple-Undo-redo-library-for-Csharp-NET when adding Undo / Redo functions to existing projects.

0
source share

Source: https://habr.com/ru/post/650101/


All Articles