6.命令模式
阿新 • • 發佈:2017-09-02
實現 應該 tip string was 命令 imp method generate
1.定義命令接口
public interface Command { public void execute(); }
2.具體需要調用到的方法的類
public class Light { public void on(){ System.out.println("Light on"); } public void off(){ System.out.println("Light off"); } } public class GarageDoor { public void up(){ System.out.println("Garage Door is Open"); } public void down(){ System.out.println("Garage Door Down"); } public void stop(){ System.out.println("GarageDoor stop"); } public void lightOn(){ System.out.println("GarageDoor LightOn "); } public void lightOff(){ System.out.println("GarageDoor lIghOff"); } }
3.這些具體要調用到的方法的類的對應具體命令類
public class LightOnCommand implements Command { private Light light; public LightOnCommand(Light light){ this.light=light; } public void execute() { // TODO Auto-generated method stub this.light.on(); } } public class GarageDoorOpenCommand implements Command{ private GarageDoor door; public GarageDoorOpenCommand(GarageDoor door){ this.door=door; } public void execute() { // TODO Auto-generated method stub this.door.up(); } }
4.客戶程序
public class SimpleRemoteControl { private Command command; public void setCommand(Command command){ this.command=command; } public void buttonWasPressed(){ this.command.execute(); } }
5.應用
public class App { public static void main(String[] args) { SimpleRemoteControl control=new SimpleRemoteControl(); //1 Light light=new Light(); Command lightOn=new LightOnCommand(light); control.setCommand(lightOn); control.buttonWasPressed(); //2 GarageDoor door=new GarageDoor(); Command doorOpen=new GarageDoorOpenCommand(door); control.setCommand(doorOpen); control.buttonWasPressed(); } }
6.結果應該是這樣的
tip: 而命令模式中,經典的批處理,撤銷,重做。其實就是在客戶程序中,比如用list集合緩存一批命令對象,批調用就實現了批處理,然後在每次調用時也緩存這次調用的命令方法,下次重新執行最後一次執行的相反的緩存命令或此緩存命令就實現撤銷或重做了。
6.命令模式