1,定义命令接口
[
html]
package com.pattern.command;
public interface Command {
public void execute();
}
2,接口的实现类
[html]
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,命令的具体执行者
[html]
package com.pattern.command;
public class Light {
public void on(){
System.out.println("turn on the light!");
}
}
4,控制器类
[html]
package com.pattern.command;
public class SimpleRemoteControl {
Command slot;
public SimpleRemoteControl(){}
public void setCommand(Command command){
slot = command;
}
public void buttonWasPressed(){
slot.execute();
}
}
5,测试类
[html]
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!