双曲空间多模态学习在恶意软件检测中的应用
2026/6/9 7:11:10
将“请求”(操作)封装成一个独立的对象,从而让发送者和执行者完全解耦,支持撤销、重做、队列、日志等高级功能。
图形编辑器(如Photoshop/GIMP)的“撤销/重做”:
不用命令模式,你会直接这样写:
editor.brighten();// 菜单直接调用编辑器方法editor.crop();// 想加撤销?每个操作都要在编辑器里写undo逻辑,耦合到死// 想队列批量执行?想记录操作日志?想宏命令?全寄!| 项目 | 责任链(Chain of Responsibility) | 装饰器(Decorator) | 命令(Command) |
|---|---|---|---|
| 核心意图 | 请求沿链找处理者 | 动态叠加行为 | 将操作封装成对象,支持撤销/队列 |
| 关键元素 | next指针 + 可中断 | 包装链 + 全执行 | execute() + undo() |
| 执行时机 | 立即沿链传递 | 立即层层执行 | 可延迟、可队列、可撤销 |
| 典型场景 | Web中间件、事件过滤 | 流加密/日志 | 编辑器撤销、事务、宏命令、线程池 |
| 口号 | “传下去,直到有人接” | “层层叠加” | “命令即对象,想干啥都行” |
#include<iostream>#include<memory>#include<vector>#include<string>usingnamespacestd;// 1. 接收者(真正干活的对象)classImageEditor{string state="原始图片";public:voidbrighten(){state+=" → 调亮";cout<<"[Editor] 执行调亮 → 当前状态: "<<state<<endl;}voidcrop(){state+=" → 裁剪";cout<<"[Editor] 执行裁剪 → 当前状态: "<<state<<endl;}voidunbrighten(){/* 实际项目里恢复状态 */cout<<"[Editor] 撤销调亮\n";}voiduncrop(){cout<<"[Editor] 撤销裁剪\n";}voidshow()const{cout<<"当前图片状态: "<<state<<endl;}};// 2. 命令接口classCommand{public:virtual~Command()=default;virtualvoidexecute()=0;virtualvoidundo()=0;};// 3. 具体命令(绑定接收者 + 操作)classBrightenCommand:publicCommand{ImageEditor*editor;public:explicitBrightenCommand(ImageEditor*e):editor(e){}voidexecute()override{editor->brighten();}voidundo()override{editor->unbrighten();}};classCropCommand:publicCommand{ImageEditor*editor;public:explicitCropCommand(ImageEditor*e):editor(e){}voidexecute()override{editor->crop();}voidundo()override{editor->uncrop();}};// 4. 调用者(维护命令历史栈)classCommandHistory{vector<unique_ptr<Command>>history;ImageEditor&editor;public:explicitCommandHistory(ImageEditor&e):editor(e){}voidexecuteCommand(unique_ptr<Command>cmd){cmd->execute();history.push_back(move(cmd));// 入栈}voidundo(){if(!history.empty()){history.back()->undo();history.pop_back();}else{cout<<"无操作可撤销\n";}}voidshowState()const{editor.show();}};intmain(){ImageEditor editor;CommandHistoryhistory(editor);// 用户操作history.executeCommand(make_unique<BrightenCommand>(&editor));history.executeCommand(make_unique<CropCommand>(&editor));history.executeCommand(make_unique<BrightenCommand>(&editor));history.showState();// 原始图片 → 调亮 → 裁剪 → 调亮cout<<"\n=== 用户按 Ctrl+Z 撤销 ===\n";history.undo();// 撤销最后一次调亮history.undo();// 撤销裁剪history.showState();// 回到只调亮一次的状态}输出:
[Editor] 执行调亮 → 当前状态: 原始图片 → 调亮 [Editor] 执行裁剪 → 当前状态: 原始图片 → 调亮 → 裁剪 [Editor] 执行调亮 → 当前状态: 原始图片 → 调亮 → 裁剪 → 调亮 当前图片状态: 原始图片 → 调亮 → 裁剪 → 调亮 === 用户按 Ctrl+Z 撤销 === [Editor] 撤销调亮 [Editor] 撤销裁剪 当前图片状态: 原始图片 → 调亮“操作封装成对象,撤销重做随便搞;
菜单快捷键解耦,历史栈里随便跳!”
当你需要“支持撤销/重做、延迟执行、队列操作、日志记录”等高级行为,且不想让调用者和具体操作耦合时,
立刻上命令模式——把“要做什么”封装成对象,想怎么玩都行!
现在,命令模式彻底说透了!
下一期是解释器模式(Interpreter)[15],虽然是GoF里最冷门的,但也有真实用途。