data structure used to implement UNDO and REDO option

前端 未结 5 800
天命终不由人
天命终不由人 2020-12-02 05:19

I want to implement UNDO and REDO option(as we see in MS word etc). Can you suggest me a data structure for it, and how can i implement it.?

5条回答
  •  伪装坚强ぢ
    2020-12-02 06:05

    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',))
    

提交回复
热议问题