设计模式-行为型模式,命令模式(11)
命令模式(Command Pattern)是一种数据驱动的设计模式,它属于行为型模式。请求以命令的形式包裹在对象中,并传给调用对象。调用对象寻找可以处理该命令的合适的对象,并把该命令传给相应的对象,该对象执行命令。
现在多数应用都有撤销操作。虽然难以想象,但在很多年里,任何软件中确实都不存在撤销
操作。撤销操作是在1974年引入的(请参考网页[t.cn/Rqr3N22]),但Fortran和Lisp分别早在1957
年和1958年就已创建了撤销操作(请参考网页[t.cn/Rqr3067]),这两门语言仍在被人广泛使用。
在那些年里,我真心不想使用应用软件。犯了一个错误,用户也没什么便捷方式能修正它。
import os verbose = True class RenameFile: def __init__(self, path_src, path_dest): self.src, self.dest = path_src, path_dest def execute(self): if verbose: print("[renaming '{}' to '{}']".format(self.src, self.dest)) os.rename(self.src, self.dest) def undo(self): if verbose: print("[renaming '{}' back to '{}']".format(self.dest, self.src)) os.rename(self.dest, self.src) class CreateFile: def __init__(self, path, txt='hello world\n'): self.path, self.txt = path, txt def execute(self): if verbose: print("[creating file '{}']".format(self.path)) with open(self.path, mode='w', encoding='utf-8') as out_file: out_file.write(self.txt) def undo(self): delete_file(self.path) class ReadFile: def __init__(self, path): self.path = path def execute(self): if verbose: print("[reading file '{}']".format(self.path)) with open(self.path, mode='r', encoding='utf-8') as in_file: print(in_file.read(), end='') def delete_file(path): if verbose: print("deleting file '{}'".format(path)) os.remove(path) def main(): orig_name, new_name = 'file1', 'file2' commands = [] for cmd in CreateFile(orig_name), ReadFile(orig_name), RenameFile(orig_name, new_name): commands.append(cmd) [c.execute() for c in commands] answer = input('reverse the executed commands? [y/n] ') if answer not in 'yY': print("the result is {}".format(new_name)) exit() for c in reversed(commands): try: c.undo() except AttributeError as e: pass if __name__ == '__main__': main()
反对极端面向过程编程思维方式,喜欢面向对象和设计模式的解读,喜欢对比极端面向过程编程和oop编程消耗代码代码行数的区别和原因。致力于使用oop和36种设计模式写出最高可复用的框架级代码和使用最少的代码行数完成任务,致力于使用oop和设计模式来使部分代码减少90%行,使绝大部分py文件最低减少50%-80%行的写法。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· AI 智能体引爆开源社区「GitHub 热点速览」