命令模式
文章目录
定义:将请求转换为一个包含与请求相关的所有信息的独立对象。该转换让你能根据不同的请求将方法参数化、 延迟请求执行或将其放入队列中。
java 中的 Runnable
接口使用的就是命令模式。
命令模式中包含4类角色,分别是
- 触发者(invoker):负责初始化请求,会持有命令的引用
- 命令接口(command):定义命令方法
- 具体命令:将请求委派给接收者,会持有接收者的引用
- 接收者(Receive):处理具体的业务逻辑
实现代码为:
//2.命令接口
@FunctionalInterface
public interface Command {
void execute();
}
//4.接收者类
public class Light {
public void on() {
System.out.println("on");
}
public void off() {
System.out.println("off");
}
}
// 3.具体命令
public class LightOnCommand implements Command{
private Light light;
public LightOnCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.on();
}
}
// 3.具体命令
public class LightOffCommand implements Command{
private Light light;
public LightOffCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.off();
}
}
//1.触发者
public class Button {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void pressButton(){
command.execute();
}
}
// 客户端代码
Light light=new Light();
Command lightOnCommand= new LightOnCommand(light);
Command lightOffCommand= new LightOffCommand(light);
Button button=new Button();
button.setCommand(lightOnCommand);
button.pressButton();
button.setCommand(lightOffCommand);
button.pressButton();
命令模式的优点是:
- 符合单一职责原则,将调用者和接收者解耦
- 符合开闭原则,容易扩展 command 命令,不需要修改客户端代码 缺点是代码会随着命令越多变得越复杂。因为如果存在 N 条命令,则需要 N 个 command 子类
文章作者 梧桐碎梦
上次更新 2023-04-16 10:26:08