【命令模式】将”请求“封装成对象,以便使用不同的请求,队列或者日志来参数化其他对象,命令模式也支持可撤销的操作。
1,定义命令接口
package com.pattern.command; public interface Command { public void execute(); }
2,接口的实现类
package com.pattern.command; public class LightOnCommand implements Command{ Light light; public LightOnCommand(Light light){ this.light = light; } /** * @see com.pattern.command.Command#execute() */ @Override public void execute() { light.on(); } }
3,命令的具体执行者
package com.pattern.command; public class Light { public void on(){ System.out.println("turn on the light!"); } }
4,控制器类
package com.pattern.command; public class SimpleRemoteControl { Command slot; public SimpleRemoteControl(){} public void setCommand(Command command){ slot = command; } public void buttonWasPressed(){ slot.execute(); } }
5,测试类
package com.pattern.command; 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(); } }
输出结果:
turn on the light!