命令模式:ide
解決「請求者」與「執行者」之間的耦合。this
好比:spa
一個麪館子裏來個一位客人,客人在菜單上寫了「魚香肉絲蓋飯」並交給了服務員,服務員把菜單拿到後堂,交給了大廚!!!線程
其中,訂單就起解耦的做用!!!code
原理:對象
Command 是命名模式的抽象接口,全部的具體命名都須要實現這個接口blog
Client 至關於上面例子中的客人接口
Receiver 至關於上面例子中的廚師,它最後進行具體的實施隊列
Invoker 至關於例子中的服務員,在Invoker中,實例化具體的Command對象rem
ConcreteCommand 至關於訂單,實現了Command接口
例子:
好比:
實現一個遙控器,能夠控制電燈的開或者關!
package Command; public interface Command { public void execute(); }
package Command; public class Light { public void on() { System.out.println("light up"); } public void off() { System.out.println("douse the glim"); } }
package Command; public class LightOnCommand implements Command{ Light light; public LightOnCommand(Light light) { this.light = light; } public void execute() { light.on(); } }
package Command; public class SimpleRemoteControl { Command slot; public SimpleRemoteControl() {} public void setCommand(Command command) { this.slot = command; } public void buttonWasPressed() { slot.execute(); } }
public class Main { public static void main(String[] args) { SimpleRemoteControl remote = new SimpleRemoteControl(); Light light = new Light(); LightOnCommand lightOn = new LightOnCommand(light); remote.setCommand(lightOn); remote.buttonWasPressed(); } }
應用場景:
線程池、隊列請求、記錄宏 。。。