【命令模式】將”請求“封裝成對象,以便使用不同的請求,隊列或者日誌來參數化其他對象,命令模式也支持可撤銷的操作。
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!