大家好,我是一个工作20多年的老程序员,把自己工作中积累的经验慢慢给大家分享
设计模式中“命令模式”的应用解析
在设计一个智能家电遥控器系统时,需支持对灯光、空调等设备的操作记录与撤销功能。最适合的设计模式是()。A. 观察者模式B. 命令模式C. 迭代器模式D. 访问者模式
考点解析
本题核心考查命令模式的核心思想与适用场景:
详细分析过程
题干要求支持操作记录与撤销,需封装操作并保存历史:
工作中的实际应用
早年开发文本编辑器时,实现“撤销”功能直接在按钮点击事件中写逻辑:
// 直接操作接收者(文本框) buttonUndo.addActionListener(e -> { // 硬编码撤销逻辑,与文本框强耦合 textArea.setText(previousText); }); |
这种方式导致新增操作(如“剪切”“粘贴”)时,撤销逻辑需大量修改,且无法记录多步历史。
改用命令模式后,定义命令接口:
public interface Command { void execute(); void undo(); } |
具体命令类:
public class InsertCommand implements Command { private TextEditor editor; private String text; private int position; public InsertCommand(TextEditor editor, String text, int position) { this.editor = editor; this.text = text; this.position = position; } public void execute() { editor.insert(text, position); } public void undo() { editor.delete(position, text.length()); } } |
调用者(遥控器)管理命令历史:
public class EditorInvoker { private Stack<Command> history = new Stack<>(); public void executeCommand(Command cmd) { cmd.execute(); history.push(cmd); } public void undo() { if (!history.isEmpty()) { history.pop().undo(); } } } |
客户端使用:
EditorInvoker invoker = new EditorInvoker(); invoker.executeCommand(new InsertCommand(editor, "hello", 0)); invoker.undo(); // 撤销插入操作 |
后来新增“删除”“替换”等操作时,只需添加对应命令类,撤销逻辑自动生效。多步撤销也通过历史栈轻松实现,系统扩展性大幅提升。
但命令模式也会增加类数量,曾因每个小操作都建命令类导致类膨胀。后来通过合并相似命令(如将“插入单个字符”和“插入字符串”合并),缓解了这一问题。
答案总结
命令模式通过封装请求实现操作的记录与撤销,是实现“事务”“撤销”功能的理想选择。
答案:B
如果文章对你有提升,帮忙点赞,分享,关注。非常感谢