用于实施UNDO和REDO选项的数据结构

时间:2009-03-31 14:05:28

标签: data-structures design-patterns undo-redo

我想实现UNDO和REDO选项(正如我们在MS word等中看到的那样)。你能为我建议一个数据结构,我该如何实现呢?

5 个答案:

答案 0 :(得分:100)

它不是数据结构,而是设计模式。您正在寻找Command Pattern

标准是将Command对象保留在堆栈中以支持多级撤消。为了支持重做,第二个堆栈会保留你已经完成的所有命令。因此,当您弹出撤消堆栈以撤消命令时,您可以将弹出的相同命令推送到重做堆栈。重做命令时,反向执行相同的操作。弹出重做堆栈并将弹出的命令推回到撤消堆栈中。

答案 1 :(得分:35)

实际上,此功能的标准模式(Gang of Four,even)是Memento

此外,虽然大多数程序使用Undo / Redo堆栈,但某些文本编辑器的功能更喜欢Undo / Redo ,这样如果它们撤消一些命令它们就不会丢失它们的整个历史记录,试试新的,改变他们的想法。

答案 2 :(得分:2)

Objective-C Cocoa有一个记录良好的anwser,名为NSUndoManager

答案 3 :(得分:2)

您可以使用命令模式存档撤消/重做

检查这些样本:

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

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

答案 4 :(得分:2)

这是命令模式的经典案例。以下是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',))