设计模式(python实现)--命令模式(Command)

2020-01-28  本文已影响0人  远行_2a22

Command

动机(Motivation)

模式定义

将一个请求(行为)封装成一个对象,从而使你可用不用的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。
——《设计模式》GoF

要点总结

例子

# -*- coding:utf-8 -*-
import os

class RenameFile:
    def __init__(self, path_src, path_dst):
        self.src, self.dst = path_src, path_dst

    def execute(self):
        print("[renaming '{}' to '{}']".format(self.src, self.dst))
        os.rename(self.src, self.dst)

    def undo(self):
        print("[rename undo: renaming '{}' back to '{}']".format(self.dst, self.src))
        os.rename(self.dst, self.src)


class CreateFile:
    def __init__(self, path, txt='hello world\n'):
        self.path, self.txt = path, txt

    def execute(self):
        print("[creating file '{}']".format(self.path))
        with open(self.path, mode='w') as out_file:
            out_file.write(self.txt)

    def undo(self):
        os.remove(self.path)
        print("[creat undo: delete file '{}']".format(self.path))


if __name__ == '__main__':
    cmd_list = []
    create_cmd = CreateFile(r'create_test.text')
    cmd_list.append(create_cmd)
    rename_cmd = RenameFile(r'create_test.text', r'rename_test.text')
    cmd_list.append(rename_cmd)
    for cmd in cmd_list:
        cmd.execute()

    start_undo = False
    if start_undo:
        print('*'*30)
        print('start undo')
        # 注意命令需要倒序撤销
        for cmd in reversed(cmd_list):
            cmd.undo()

通过将操作封装成cmd对象,存入list,可以进行撤销等操作。

上一篇 下一篇

猜你喜欢

热点阅读