命令模式定义
将请求封装成对象,以便使用不同的请求,队列,或者日志来参数化其他对象。命令模式也可以支持可测销操作。
命令模式示意图
遥控器控制电灯打开的java代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| public class Light { public void on(){ log.info("light on..."); } } public interface Command { void execute(); } public class LightOnCommand implements Command { Light light; public LightOnCommand(Light light) { this.light=light; } @Override public void execute() { this.light.on(); } } public class SimpleRemoteControl { Command slot; public SimpleRemoteControl(){} public void setCommand(Command command){ this.slot=command; } public void buttonWasPressed(){ this.slot.execute(); } } public class RemoteControlTest { public static void main(String[] args) { SimpleRemoteControl remote=new SimpleRemoteControl(); Light light=new Light(); LightOnCommand lightOnCommand=new LightOnCommand(light); remote.setCommand(lightOnCommand); remote.buttonWasPressed(); } }
|