2026-10-22 15:30:59
命令模式是一种行为设计模式,它将请求或操作封装为一个对象,从而使你可以参数化客户端对象,对请求排队或记录请求日志,以及支持可撤销的操作。以下是对命令模式的详细解析:
核心概念以下是一个简单的JavaScript命令模式实现示例:
// 接收者类class Receiver { execute() { console.log('接收者执行请求'); }}// 命令对象类class Command { constructor(receiver) { this.receiver = receiver; } execute() { console.log('命令对象->接收者->对应接口执行'); this.receiver.execute(); }}// 发布者类class Invoker { constructor(command) { this.command = command; } invoke() { console.log('发布者发布请求'); this.command.execute(); }}// 客户端代码const warehouse = new Receiver(); // 仓库(接收者)const order = new Command(warehouse); // 订单(命令对象)const client = new Invoker(order); // 客户(发布者)client.invoke(); // 客户下单应用场景优点:
降低系统的耦合度,发布者与接收者之间通过命令对象解耦。
新的命令可以很容易地加入到系统中,提高系统的可扩展性。
可以比较容易地设计一个组合命令或宏命令。
为请求的撤销和重做操作提供了一种设计和实现方案。
缺点:
可能会导致某些系统有过多的具体命令类,增加了系统的复杂性。
增加了额外的对象创建和内存消耗。
宏命令是一组命令的集合,可以一次性执行多个命令:
// 宏命令对象class MacroCommand { constructor() { this.commandList = []; // 缓存子命令对象 } add(command) { // 向缓存中添加子命令 this.commandList.push(command); } execute() { // 对外命令执行接口 // 遍历自命令对象并执行其 execute 方法 for (const command of this.commandList) { command.execute(); } }}// 命令对象const openWechat = { execute: () => { console.log('打开微信'); }};const openChrome = { execute: () => { console.log('打开Chrome'); }};const openEmail = { execute: () => { console.log('打开Email'); }};const macroCommand = new MacroCommand();macroCommand.add(openWechat); // 宏命令中添加子命令macroCommand.add(openChrome); // 宏命令中添加子命令macroCommand.add(openEmail); // 宏命令中添加子命令macroCommand.execute(); // 执行宏命令傻瓜命令与智能命令智能命令与策略模式类似,但实现目标不同。策略模式中实现的目标是一致的,只是实现算法不同;而智能命令的解决问题更广,目标更具散发性。
总结命令模式通过将请求或操作封装为对象,实现了发布者与接收者之间的解耦,提高了系统的灵活性和可扩展性。它适用于需要将请求排队、记录请求日志、支持撤销操作等场景。然而,命令模式也可能导致系统中有过多的具体命令类,增加了系统的复杂性。因此,在使用命令模式时,需要权衡其优缺点,根据具体场景进行选择。