命令模式,其实就是进一步封装,把方法调用封装起来,head first中举了一个很生动的例子,饭店中点餐的流畅如下:客户点了订单并交给服务端,然后女招待把订单交给大厨的师傅,大师傅最后呈现出一道可口的菜肴。
在这个过程中,客户只需要知道来饭店点好菜单就可以等吃饭了,服务员也是只需要知道把订单交给大厨,而大厨也只需要如何根据订单来做错了事情。
实现一个打开电灯的命令
public interface Command {
public void execute();
}
public class LightOnCommand implements Command {
Light light;
public LightOnCommand(Light light) {
this.light = light;
}
public void execute() {
light.on();
}
}
public class SimpleRemoteControl {
Command slot;
public SimpleRemoteControl() {}
public void setCommand(Command command) {
slot = command;
}
public void buttonWasPressed() {
slot.execute();
}
}
主测试类:
public class RemoteControlTest {
public static void main(String[] args) {
SimpleRemoteControl remote = new SimpleRemoteControl();
Light light = new Light();
LightOnCommand lightOn = new LightOnCommand(light);
remote.setCommand(lightOn);
remote.buttonWasPressed();
}
}
将请求和接受都包装成对象,请求方不需要知道接收方的接口以及请求信息,从而使俩个对象松耦合,代码结构更容容易扩展。
待补充。。。