命令模式:将请求封装成对象,以便使用不同的请求、队列或者日志来参数化其他对象。命令模式也支持可撤销的操作。
简而言之:命令模式就是将方法调用封装起来。
相关代码:
(1)先定义一个command接口:
public interface Command {
public void execute();
}
(2)定义一个Light类作为command执行者(receiver)
public class Light {
String location = null;
public Light(String location) {
this.location = location;
}
public void on() {
System.out.println(location + " Turn light on.");
}
public void off() {
System.out.println(location + " Turn light off.");
}
}
(3)继承command接口,定义一个command类,采用组合方式将相关的操作传递给实际执行者
public class LightOnCommand implements Command{
Light light;
public LightOnCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
// TODO Auto-generated method stub
light.on();
}
}
(4)创建一个command调用者
public class SimpleRemoteControl {
Command slot;
public void setCommand(Command command) {
this.slot = command;
}
public void buttonWasPressed() {
slot.execute();
}
}
(4)测试代码
public class RemoteControlTest {
public static void main(String[] args) {
SimpleRemoteControl remote = new SimpleRemoteControl();
Light light = new Light("Living room");
LightOnCommand lightOn = new LightOnCommand(light);
remote.setCommand(lightOn);
remote.buttonWasPressed();
}
}
(5)测试结果
Living room Turn light on.