命令模式(Command Pattern)是一种行为型设计模式。它将请求封装成一个对象,从而使你能够用不同的请求、队列和日志请求以及支持可撤销操作。
简单来说,命令模式通过把请求封装成对象的方式解耦了请求的发送者与接收者,使得客户端可以以不同的方式来请求服务,而无需直接了解接收者的实现。
命令模式通常由以下几个角色组成:
execute(),用于执行请求。execute() 方法中调用接收者的相应操作。execute() 方法来发出请求。请求者只关心命令接口,而不关心命令如何被执行。+------------+ +-----------------+ +-------------+
| Client | ---> | ConcreteCommand | ---> | Receiver |
+------------+ +-----------------+ +-------------+
| execute() |
v
+-------------+
| Invoker |
+-------------+
|
+-------------+
| Command |
+-------------+ConcreteCommand(具体命令)对象,并将 Receiver(接收者)对象传递给它。ConcreteCommand 对象传递给 Invoker(请求者)。execute() 方法,从而触发接收者的实际操作。通过这种方式,命令的发送者(请求者)和接收者(具体执行的对象)解耦,发送者只关心命令的接口,而无需了解命令如何被执行。
下面通过一个具体的代码示例来演示命令模式的实现。假设我们要实现一个简单的遥控器控制灯的开关操作。
// Command 接口
public interface Command {
void execute(); // 执行命令
}2. 具体命令类
// 开灯命令
public class LightOnCommand implements Command {
private Light light;
public LightOnCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.turnOn();
}
}
// 关灯命令
public class LightOffCommand implements Command {
private Light light;
public LightOffCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.turnOff();
}
}3. 接收者(Receiver)
// 接收者:Light(灯)
public class Light {
public void turnOn() {
System.out.println("The light is ON");
}
public void turnOff() {
System.out.println("The light is OFF");
}
}4. 请求者(Invoker)
// 请求者:遥控器
public class RemoteControl {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void pressButton() {
command.execute(); // 执行命令
}
}5. 客户端(Client)
public class Client {
public static void main(String[] args) {
// 创建接收者(灯)
Light light = new Light();
// 创建具体命令(开灯和关灯)
Command lightOn = new LightOnCommand(light);
Command lightOff = new LightOffCommand(light);
// 创建请求者(遥控器)
RemoteControl remote = new RemoteControl();
// 设置命令并按下按钮
remote.setCommand(lightOn);
remote.pressButton(); // 输出: The light is ON
remote.setCommand(lightOff);
remote.pressButton(); // 输出: The light is OFF
}
}Command 接口,而不需要修改现有代码,符合开闭原则。命令模式在实际项目中有许多应用,例如:
命令模式通过将请求封装成对象,从而使请求的发送者与接收者解耦。这种模式非常适合需要支持撤销操作、日志记录、队列请求等场景。尽管它引入了大量的命令类,但它的灵活性和可扩展性使得它在很多大型系统中得到了广泛应用。
如果您有任何问题或建议,欢迎留言讨论。