How to implement undo functionality?

半世苍凉 提交于 2020-05-24 23:01:26

问题


In my application I want to provide the user with a small undo functionality. There aren't many actions than can be undone by the user. Particularly the actions are:

  • Add notes to an object
  • Color an object
  • Tag a objcet with a string

Now I thought about how to implement this. I first thought of a Action Class that is the abstract base class for the 3 different actions that can be taken by the user. Every time the user takes on of these actions, a new appropriate instance of a subclass of this abstract Action class is created and inserted into a list that contains all actions.

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

Now I was thinking what has to be stored in such an action object:

  • the state of the object before the action
  • the actual action that was taken (e.g. the string that was added to a object's notes)

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

Are there any other things I should consider?


回答1:


Undo/redo is commonly implemented with the Command Pattern. The Action class can be used as the basis for this, but you need a 'do' action and an 'undo' action within each command. Here is an example of this in practice. You should probably store the commands executed in a stack as it makes it much easier to implement and much easier for the user to follow.




回答2:


You could do something simple like this:

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;
}



回答3:


you should implement the Command Pattern for every action you want undo:

how to implement undo/redo operation without major changes in program




回答4:


For Correct and proven implememtation for UNDO functionality is Command Pattern




回答5:


Its hard to overlook this Simple-Undo-redo-library-for-Csharp-NET when adding Undo/Redo functionality to existing projects.



来源:https://stackoverflow.com/questions/4431920/how-to-implement-undo-functionality

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!