Python设计模式:命令模式

设计模式十二:命令模式

什么是命令模式

将一个操作(撤销、重做、复制、粘贴等)封装成一个对象。

使用优势

不需要直接执行一个命令,命令可以按照希望执行。
调用命令的对象与知道如何执行命令的对象解耦。
调用者无需知道命令的任何实现细节。
可以把多个命令组织起来,调用者能够按顺序执行。

使用场景

如果一个操作需要多次被调用,并且需要在不同场景调用,那么就可以将其封装成一个对象

典型案例

餐馆点餐,每个账单都是独立的,但是每个账单都可以执行许多不同命令,
比如 点菜命令(可以点不同菜加入到烹煮队列里),撤销命令等

实例代码

import os
class RenameFile:
    
    def __init__(self,srcpath,destpath):
        self.src,self.dest = srcpath,destpath

    def execute(self):
        os.rename(self.src,self.dest)
    
    def undo(self):
        os.rename(self.dest,self.src)

class CreateFile:

    def __init__(self,path,txt='11111111111111\n'):
        self.path,self.txt = path,txt

    def execute(self):
        with open(self.path,mode = 'w',encoding='utf-8') as f:
            f.write(self.txt)
    
    def undo(self):
        delete_file(self.path)

class ReadFile:

    def __init__(self,path):
        self.path = path
    
    def execute(self):
        with open(self.path,mode = 'r' ,encoding='utf-8') as f:
            print(f.read(),end='')

# 删除文件的命令可以是一个方法,不一定是要和其他命令一样
def delete_file(path):
    os.remove(path)

def main():
    orig , new = 'file1','file2'
    command = []
    for cmd in CreateFile(orig),ReadFile(orig),RenameFile(orig,new):
        command.append(cmd)
    [c.execute() for c in command]
    answer = input('reverse the executed command?[y/n]')
    if answer not in 'yY':
        print('the result is {}',format(new))
        exit()
    # 执行撤销动作时,需要从后往前撤销,所以需要reversed方法来反转列表
    for c in reversed(commands):
        try:
            c.undo()
        except AttributeError as e:
            pass

if __name__ == "__main__":
    main()

你可能感兴趣的:(设计模式,设计模式,python)