命令模式:
将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤消的操作。
UML图:
解析UML图:
示例:
现在需要开发一个遥控器的API,当遥控器的某个按钮按下去之后,插座上对应的机器能够操作.如灯亮,风扇转等,但注意了插座对应的设备是可变化的,或者说仍有空余的插座是预留给新设备的.
采用Command模式代码如下:
package com.lwf.command;
public interface Command {
public void excute();
}
package com.lwf.command;
public class LineOnCommand implements Command {
Light light;
public LineOnCommand(Light light){
this.light = light;
}
public void excute() {
light.on();
}
}
package com.lwf.command;
public class LineOffCommand implements Command {
Light light;
LineOffCommand(Light light){
this.light = light;
}
public void excute() {
light.off();
}
}
package com.lwf.command;
public class Light {
public void on(){
System.out.println("on");
}
public void off() {
System.out.println("off");
}
}
package com.lwf.command;
public class SimpleRemoteControl {
Command command;
public void setCommand(Command command){
this.command = command;
}
public void buttonWasPressed(){
command.excute();
}
}
package com.lwf.command;
public class Client {
/*
* 客户端负责创建command对象并设置接收者light
*/
public static void main(String[] args) {
//客户client创建command对象并设置接收者light
Light light = new Light();
Command command = new LineOnCommand(light);
//调用者(遥控器)invoker,持有command对象,并设置具体的Command对象.在自己的方法中调用command的excute方法.
SimpleRemoteControl s = new SimpleRemoteControl();
s.setCommand(command);
s.buttonWasPressed();
command = new LineOffCommand(light);
s.setCommand(command);
s.buttonWasPressed();
}
}
测试结果:
on
off