【设计模式】—— 命令模式Commond
生活随笔
收集整理的這篇文章主要介紹了
【设计模式】—— 命令模式Commond
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言:【模式總覽】——————————by xingoo
模式意圖
將一個請求封裝成一個對象,從而對這個命令執行撤銷、重做等操作。
典型的Eclipse開發中,編輯器的操作就需要用到這個模式,比如Undo、Redo等等。
另外這個模式使得一個命令的觸發與接收解耦,這樣我們就可以演變成把感興趣的對象接收這個命令,當命令觸發時,這些對象就會執行操作。這個機制也是java事件的處理方式。
應用場景
1 命令抽象成對象
2 在不同的時刻,指定或者排隊命令
3 支持 Undo或者Redo等操作
4 修改日志,當系統崩潰時,利用修改日志執行撤銷
5 原語操作上構造一個高層系統(不理解)
模式結構
Invoker 命令的觸發者,觸發一個命令的執行。
/*** 命令的觸發者,發送命令* @author xingoo**/ class Invoker{private Commond commond;public Invoker(Commond commond) {this.commond = commond;}public void action(){commond.excute();} }Receiver 命令的接受者,針對命令,執行一定的操作。
/*** 命令的接受者,負責接收命令,進行處理* @author xingoo**/ class Receiver{public Receiver() {}public void action(){System.out.println("Action of receiver!");} }Commond 命令的抽象接口
/*** 命令接口,定義命令的統一接口* @author xingoo**/ interface Commond{public void excute(); }ConcreteCommond 具體的命令,關聯一個接收者對象,當命令執行時,執行這個接收者對應的操作。
/*** 具體的命令* @author xingoo**/ class ConcreteCommond implements Commond{private Receiver receiver;public ConcreteCommond(Receiver receiver) {this.receiver = receiver;}public void excute() {receiver.action();}}全部代碼
1 package com.xingoo.Commond; 2 /** 3 * 命令的觸發者,發送命令 4 * @author xingoo 5 * 6 */ 7 class Invoker{ 8 private Commond commond; 9 10 public Invoker(Commond commond) { 11 this.commond = commond; 12 } 13 14 public void action(){ 15 commond.excute(); 16 } 17 } 18 /** 19 * 命令的接受者,負責接收命令,進行處理 20 * @author xingoo 21 * 22 */ 23 class Receiver{ 24 25 public Receiver() { 26 27 } 28 29 public void action(){ 30 System.out.println("Action of receiver!"); 31 } 32 } 33 /** 34 * 命令接口,定義命令的統一接口 35 * @author xingoo 36 * 37 */ 38 interface Commond{ 39 public void excute(); 40 } 41 /** 42 * 具體的命令 43 * @author xingoo 44 * 45 */ 46 class ConcreteCommond implements Commond{ 47 48 private Receiver receiver; 49 50 public ConcreteCommond(Receiver receiver) { 51 this.receiver = receiver; 52 } 53 54 public void excute() { 55 receiver.action(); 56 } 57 58 } 59 /** 60 * 客戶端調用者 61 * @author xingoo 62 * 63 */ 64 public class Client { 65 public static void main(String[] args) { 66 Receiver receiver = new Receiver(); 67 Commond commond = new ConcreteCommond(receiver); 68 System.out.println("Commond register in here!"); 69 70 try { 71 Thread.sleep(3000); 72 } catch (InterruptedException e) { 73 // TODO Auto-generated catch block 74 e.printStackTrace(); 75 } 76 77 System.out.println("Commond excute in here!"); 78 Invoker invoker = new Invoker(commond); 79 invoker.action(); 80 } 81 } View Code運行結果
Commond register in here! Commond excute in here! Action of receiver!?
轉載于:https://www.cnblogs.com/xing901022/p/4075013.html
總結
以上是生活随笔為你收集整理的【设计模式】—— 命令模式Commond的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在win8.1 64位系统+cocos
- 下一篇: asp.net ajax控件工具集 Au