52

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

4

5 回答 5

111

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

标准是将 Command 对象保存在堆栈中以支持多级撤消。为了支持重做,第二个堆栈保留您已撤消的所有命令。因此,当您弹出撤消堆栈以撤消命令时,您会将弹出的相同命令推送到重做堆栈中。当你重做一个命令时,你反过来做同样的事情。您弹出重做堆栈并将弹出的命令推回撤消堆栈。

于 2009-03-31T14:07:24.140 回答
39

实际上,此功能(甚至是四人组)的标准模式是Memento

此外,虽然大多数程序使用撤消/重做堆栈,但某些文本编辑器的爱好者更喜欢撤消/重做,以便在撤消一些命令、尝试新命令并改变主意时不会丢失整个历史记录。

于 2009-05-26T10:30:44.723 回答
2

Objective-C Cocoa 有一个有据可查的 anwser,名为NSUndoManager

于 2009-03-31T14:13:53.267 回答
1

您可以使用命令模式来实现撤消/重做

检查这些样本:

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

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

于 2009-03-31T14:33:30.613 回答
1

这是命令模式的经典案例。以下是 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',))
于 2017-05-04T13:41:00.167 回答