简介
"用函数替换命令"(Replace Command with Function)重构手法用于简化过度设计的命令模式实现。当命令对象仅封装单一操作且无复杂状态时,应该用直接函数调用来替代。
典型代码坏味道
- 命令对象仅有一个执行方法
- 命令没有维护操作状态
- 存在不必要的对象创建开销
- 命令处理器仅做简单转发
重构步骤
-
识别简单命令
- 找到仅封装单个方法的命令类
- 分析命令对象的调用方式
- 确认没有复杂的状态管理
-
转换操作为函数
- 将execute()方法提升为独立函数
- 保持相同的参数和返回值
- 处理接口依赖关系
-
修改调用方
- 替换命令对象的实例化
- 直接调用新创建的函数
- 更新单元测试用例
-
清理残留结构
- 删除命令接口和实现类
- 移除相关工厂方法
- 处理类型依赖
示例
重构前:
interface Command {
void execute();
}
class SaveCommand implements Command {
private Document document;
public SaveCommand(Document doc) {
this.document = doc;
}
public void execute() {
document.save();
}
}
// 调用方式
new
SaveCommand(doc).
execute();
重构后:
void saveDocument(Document doc) {
doc.save();
}
// 调用方式
saveDocument(doc);
专项练习
基础练习
-
重构打印命令
class PrintCommand implements Command { public void execute() { Printer.printCurrentPage(); } }
进阶练习
-
处理带参数命令
class FilterCommand implements Command { private Image image; private int intensity; public FilterCommand(Image img, int intensity) { this.image = img; this.intensity = intensity; } public void execute() { image.applyFilter(intensity); } }
代码审查清单
优势验证
- 类数量减少50%以上
- 消除不必要的对象创建
- 提升代码可读性
风险提示
- 可能影响现有框架集成
- 需要处理接口依赖
- 降低扩展灵活性