命令模式 Command 指的是一个 执行某些特定事情的指令
应用场景:有时需要向某些对象发送请求,但并不知道请求的接受者是谁,也不知道被请求的操作是什么。这时候命令模式就负责使发送者和接受者之间解耦
命令模式把请求封装成 Command 对象,这个对象可以在程序中四处传递,接受者不需要知道发送者是谁,解开了调用者和接受者之间的耦合
假如我们正在编写一个 UI 界面,由于项目复杂,我们让一个程序员负责绘制按钮,另外的程序员负责编写点击按钮后的具体行为,这些行为都被封装在命令对象里~
让我们创建一个命令对象,用来控制 电视 的行为:
const TVCommand = {
// 打开电视
turnOn: function() {
console.log("电视已打开");
},
// 关闭电视
turnOff: function() {
console.log("电视已关闭");
},
// 切换频道
changeChannel: function(channel) {
console.log("频道已切换至 " + channel);
}
};
接下来绘制 UI 时,给按钮加上发送指令的功能(这里也是可以再次进行抽象和解耦的)
const turnOnButton = document.getElementById("turnOnButton");
const turnOffButton = document.getElementById("turnOffButton");
const changeChannelButton = document.getElementById("changeChannelButton");
turnOnButton.addEventListener("click", function() {
TVCommand.turnOn();
});
turnOffButton.addEventListener("click", function() {
TVCommand.turnOff();
});
changeChannelButton.addEventListener("click", function() {
const channel = document.getElementById("channelInput").value;
TVCommand.changeChannel(channel);
});
命令模式还有一个好处就是可以进行命令的撤销,实现方法根据场景设计,这里就不给出例子了
如同过去的几个章节,这里给出 C# 版本的例子!
using System;
// 命令接口
public interface ICommand
{
void Execute();
}
// 具体命令
public class SimpleCommand : ICommand
{
private string _message;
public SimpleCommand(string message)
{
_message = message;
}
public void Execute()
{
Console.WriteLine(_message);
}
}
// 命令执行者
public class CommandExecutor
{
public void ExecuteCommand(ICommand command)
{
command.Execute();
}
}
class Program
{
static void Main(string[] args)
{
// 创建命令和命令执行者
ICommand command = new SimpleCommand("Hello, World!");
CommandExecutor executor = new CommandExecutor();
// 执行命令
executor.ExecuteCommand(command);
}
}