美文网首页
命令行模式

命令行模式

作者: sunshining小迪儿 | 来源:发表于2018-12-21 16:37 被阅读0次
    import os
    
    
    class RenameFile(object):
        def __init__(self, src, dest):
            self.src = src
            self.dest = dest
    
        def execute(self):
            print('renaming {} to {}'.format(self.src, self.dest))
            os.rename(self.src, self.dest)
    
        def undo(self):
            print('renaming {} to {}'.format(self.dest, self.src))
            os.rename(self.dest, self.src)
    
    
    class CommandStack(object):
        def __init__(self):
            self._stack = []
    
        def push(self, command):
            command.execute()
            self._stack.append(command)
    
        def pop(self):
            command = self._stack.pop()
            command.undo()
    
        def clear(self):
            self._stack = []
    
    
    if __name__ == "__main__":
        command_stack = CommandStack()
    
        command_stack.push(RenameFile('foo.txt', 'bar.txt'))
        command_stack.push(RenameFile('bar.txt', 'baz.txt'))
    
        command_stack.pop()
        command_stack.pop()
    

    相关文章

      网友评论

          本文标题:命令行模式

          本文链接:https://www.haomeiwen.com/subject/uacvkqtx.html