命令行模式

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()

你可能感兴趣的:(命令行模式)