Java 设计模式之命令模式
本文为笔者学习《Head First设计模式》的笔记,并加入笔者自己的理解和归纳总结
命令模式将“请求”封装成对象,以便使用不同的请求、队列或者日志来参数化其他对象。命令模式也支持可撤销的操作。
结构图
遥控器(RemoteControl
)通过命令(Command
)控制灯的开关(Light
)。
public class RemoteControl {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void run() {
command.execute();
}
public void undo() {
command.undo();
}
}
public interface Command {
void execute();
void undo();
}
public class Light {
public void turnOn() {
System.out.println("light trun on");
}
public void turnOff() {
System.out.println("light trun off");
}
}
灯的开关命令
public class LightOnCommand implements Command {
private Light light;
public LightOnCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.turnOn();
}
@Override
public void undo() {
light.turnOff();
}
}
public class LightOffCommand implements Command {
private Light light;
public LightOffCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.turnOff();
}
@Override
public void undo() {
light.turnOn();
}
}
运行
public static void main(String[] args) {
Light light = new Light();
RemoteControl remoteControl = new RemoteControl();
Command command = new LightOnCommand(light);
remoteControl.setCommand(command);
remoteControl.run();
command = new LightOffCommand(light);
remoteControl.setCommand(command);
remoteControl.run();
remoteControl.undo();
}
输出
light trun on
light trun off
light trun on
相关文章
Java 设计模式