data structure used to implement UNDO and REDO option

可紊 提交于 2019-11-27 10:23:47

It isn't a data structure but a design pattern. You're looking for the Command Pattern.

The standard is to keep the Command objects in a stack to support multi level undo. In order to support redo, a second stack keeps all the commands you've Undone. So when you pop the undo stack to undo a command, you push the same command you popped into the redo stack. You do the same thing in reverse when you redo a command. You pop the redo stack and push the popped command back into the undo stack.

Actually, the standard pattern for this functionality (Gang of Four, even) is Memento.

Also, while most programs use Undo/Redo stacks, afficionados of certain text editors prefer Undo/Redo trees so that they don't lose their entire history if they undo a few commands, try a new one, and change their minds.

Objective-C Cocoa has a well documented anwser named NSUndoManager.

NinethSense

You can use Command Pattern to achive Undo/Redo

Check these samples:

http://www.codeproject.com/csharp/undoredobuffer.asp

http://www.dofactory.com/Patterns/PatternCommand.aspx

This is a classic case of Command Pattern. Following is a sample implementation of undo feature in Python :

from os import rename
class RenameFileCommand(object):
    def __init__(self, src_file, target_file):
        self.src_file=src_file
        self.target_file=target_file


    def execute(self):
        rename(self.src_file, self.target_file)

    def undo(self):
        rename(self.target_file,self.src_file)



class History(object):
    def __init__(self):
        self.commands=list()
    def execute(self, command):
        command.execute()
        self.commands.append(command)

    def undo(self):
        self.commands.pop().undo()


if __name__=='__main__':
    hist=History()
    hist.execute(RenameFileCommand( 'test1.txt', 'tmp.txt', ))
    hist.undo()
    hist.execute(RenameFileCommand( 'tmp2.txt', 'test2.txt',))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!