设计模式:命令模式(Command Pattern)
生活随笔
收集整理的這篇文章主要介紹了
设计模式:命令模式(Command Pattern)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
??命令模式(Command Pattern): 在軟件設計中,我們經常需要向某些對象發送請求,但是并不知道請求的接受者是誰,也不知道請求的操作是哪個。
? ?我們只需在程序運行時指定具體的請求接受者即可,此時,可以使用命令模式來進行設計。
? ?命令模式在spring框架的JdbcTemplate中有應用。
?
? ?通俗易懂的理解, 將軍發布命令,士兵去執行。其中有幾個角色,將軍(命令發布者),士兵(命令的具體執行者),命令(連接將軍和士兵)。
? ?Invoker是調用者(將軍), Receiver是被調用者(士兵), MyCommand是命令, 實現了Command接口,持有接受對象。
?
public interface Command {// 執行動作(操作)public void execute();// 撤銷動作(操作)public void undo(); }public class LightReceiver {public void on(){System.out.println("電燈打開了...");}public void off(){System.out.println("電燈關閉了...");} }public class LightOnCommand implements Command{LightReceiver light;public LightOnCommand(LightReceiver light){super();this.light = light;}@Overridepublic void execute() {light.on();}@Overridepublic void undo() {light.off();} }public class LightOffCommand implements Command{LightReceiver light;public LightOffCommand(LightReceiver light){super();this.light = light;}@Overridepublic void execute() {light.off();}@Overridepublic void undo() {light.on();} }public class NoCommand implements Command{@Overridepublic void execute() {}@Overridepublic void undo() {} }public class RemoteController {Command[] onCommands;Command[] offCommands;// 執行撤銷命令Command undoCommand;public RemoteController(){onCommands = new Command[5];offCommands = new Command[5];for(int i=0; i<5; i++){onCommands[i] = new NoCommand();offCommands[i] = new NoCommand();}}// 給我們按鈕設置你需要的命令即可public void setCommand(int no, Command onCommad,Command offCommad){onCommands[no] = onCommad;offCommands[no] = offCommad;}// 按下開始按鈕public void onButtonWasPushed(int no){onCommands[no].execute();// 記錄這次的操作,用于撤銷undoCommand = onCommands[no];}// 按下關閉按鈕public void offButtonWasPushed(int no){offCommands[no].execute();// 記錄這次的操作,用于撤銷undoCommand = offCommands[no];}// 按下撤銷按鈕public void undoButtonWasPushed(int no){undoCommand.undo();} }public class Client {public static void main(String[] args){// 接受者LightReceiver lightReceiver = new LightReceiver();// 創建電燈相關的開關命令LightOnCommand lightOnCommand = new LightOnCommand(lightReceiver);LightOffCommand lightOffCommand = new LightOffCommand(lightReceiver);RemoteController remoteController = new RemoteController();// 給遙控器設置相關命令remoteController.setCommand(0, lightOnCommand, lightOffCommand);remoteController.onButtonWasPushed(0);remoteController.offButtonWasPushed(0);remoteController.undoButtonWasPushed(0);} }?
總結
以上是生活随笔為你收集整理的设计模式:命令模式(Command Pattern)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 设计模式:模板方法(Template M
- 下一篇: 数据结构:回溯--解决八皇后问题