模式之命令模式
1)先创建一个command接口,里面只有一个execute() 方法等待实现
public interface Command {
void execute();
}
2)创建一个灯类作为demo
package design.mode.command;
public class Light {
public void on(){
System.out.println("light on now");
}
public void off() {
System.out.println("light off now");
}
}
- 根据Light 类作为构造函数参数,创建两个命令类LightOnCommand、LightOffCommand。命令模式的设计思路是 需要这两个命令类要实现Command接口。
public class LightOnCommand implements Command{
Light light;
LightOnCommand(Light light){
this.light = light;
}
@Override
public void execute() {
light.on();
}
}
public class LightOffCommand implements Command{
Light light;
LightOffCommand(Light light){
this.light = light;
}
@Override
public void execute() {
light.off();
}
}
4)设计一个命令调度类 RemoteCtl,用于调度命令、执行命令。依赖于实现了Command接口的命令类如LightOnCommand
public class RemoteCtl {
Command command;
public void setCommand(Command command) {
this.command = command;
}
public void execute(){
command.execute();
}
}
5)Main函数调用展示,命令模式的执行流程
public class CommandMain {
public static void main(String[] args) {
//new Light
Light light = new Light();
//new RemoteCtl
RemoteCtl remoteCtl = new RemoteCtl();
//light on
LightOnCommand lightOnCommand = new LightOnCommand(light);
remoteCtl.setCommand(lightOnCommand);
remoteCtl.execute();
//light off
LightOffCommand lightOffCommand = new LightOffCommand(light);
remoteCtl.setCommand(lightOffCommand);
remoteCtl.execute();
}
}
6)执行结果展示
light on now
light off now