命令模式:將請求封裝成對象,以便使用不同的請求、隊列、或者日誌來參數化其他對象。命令模式也支持可撤銷的操作。也就是說一個命令接收者可以綁定一系列請求,然後通過調用接受者的執行方法來執行就可以了。將一系命令通過一個命令的執行者來執行。
這裏模仿一個用遙控器對點燈開關的命令模式。
package com.modedesign.command;
/**
* @author ctt:
* @version 創建時間:2016年5月13日
* 類說明
*/
public class SimpleRemoteControlWithUndo {
Command[] onCommands;//這裏可以根據情況來定義,執行方法時可根據情況去遍歷執行命令
Command[] offCommands;
Command undoCommand;
public SimpleRemoteControlWithUndo() {
onCommands = new Command[5];
offCommands = new Command[5];
NoCommand noCommand = new NoCommand();
for (int i = 0; i < 5; i++) {
onCommands[i] = noCommand;
offCommands[i] = noCommand;
}
undoCommand = noCommand;
}
public void setCommand(int slot,Command onCommand,Command offCommand){
onCommands[slot] = onCommand;
offCommands[slot] = offCommand;
}
public void onButtonWasPressed(int slot){
onCommands[slot].excute();
undoCommand = offCommands[slot];
}
public void offButtonWasPressed(int slot){
offCommands[slot].excute();
undoCommand = offCommands[slot];
}
public void undoButtonWasPressed(){
undoCommand.undo();
}
}
package com.modedesign.command;
/**
* @author ctt:
* @version 創建時間:2016年5月13日
* 類說明 首先讓所有的命令對象實現相同的包含一個方法的接口。即excute()
* 和一個撤銷的方法undo()
*/
public interface Command {
public void excute();
public void undo();
}
package com.modedesign.command;
/**
* @author ctt:
* @version 創建時間:2016年5月13日
* 類說明
*/
public class CommandTest {
public static void main(String[] args) {
Light light = new Light();
SimpleRemoteControlWithUndo controlWithUndo
= new SimpleRemoteControlWithUndo();
controlWithUndo.setCommand(0, new LightOnCommand(light),new LightOffCommand(light));
controlWithUndo.offButtonWasPressed(0);
controlWithUndo.undoButtonWasPressed();
}
}
package com.modedesign.command;
/**
* @author ctt:
* @version 創建時間:2016年5月13日
* 類說明 light類有兩個方法,on和off
*/
public class Light {
private boolean light;
public void on(){
light = true;
System.out.println("the light is on");
}
public void off(){
light = false;
System.out.println("the light is off");
}
}
package com.modedesign.command;
/**
* @author ctt:
* @version 創建時間:2016年5月13日
* 類說明
*/
public class LightOffCommand implements Command{
private Light light;
public LightOffCommand(Light light) {
super();
this.light = light;
}
@Override
public void excute() {
light.off();;
}
@Override
public void undo() {
light.on();
}
}
package com.modedesign.command;
/**
* @author ctt:
* @version 創建時間:2016年5月13日
* 類說明實現打開電燈的命令。
*/
public class LightOnCommand implements Command{
Light light;
public LightOnCommand(Light light) {
super();
this.light = light;
}
@Override
public void excute() {
light.on();
}
@Override
public void undo() {
light.off();
}
}
package com.modedesign.command;
/**
* @author ctt:
* @version 創建時間:2016年5月13日
* 類說明
*/
public class NoCommand implements Command{
@Override
public void excute() {
// TODO Auto-generated method stub
}
@Override
public void undo() {
// TODO Auto-generated method stub
}
}