1. 程式人生 > >設計模式(14)-行為型模式-command模式

設計模式(14)-行為型模式-command模式

別名:Action或者Transaction

1.1.1      功能

                Command模式通過將請求封裝到一個物件(Command)中,並將請求的接受者(Receiver)存放到具體的ConcreteCommand類中中,從而實現呼叫操作的物件和操作的具體實現者之間的解耦。

1.1.2      結構圖與協作關係

 

備註:我認為這張圖應該在client與Invoker直接也畫條線(箭頭指向Invoker)可能更好一點.

•  C o m m a n d

                — 宣告執行操作的介面。

•  C o n c r e t e C o m m a n d ( P a s t e C om m a n d,Op e n C o m m a n d )

                — 將一個接收者物件綁定於一個動作。

                — 呼叫接收者相應的操作,以實現E x e c u t e。

•  C l i e n t ( A p p l i c t i o n )

                — 建立一個具體命令物件並設定它的接收者。

•  Invoker  ( M e n u I t e m )

                — 要求該命令執行這個請求。

•  R e c e i v e r ( D o c u m e n t,A p p li c a t i o n )

                — 知道如何實施與執行一個請求相關的操作。任何類都可能作為一個接收者。

協作關係:


•C l i e n t建立一個Co n c r e t e C o m m a n d物件並指定它的Re c e i v e r物件。
•  某I n v o k e r物件儲存該 C o n c r e t e C o m ma n d物件。
• 該In v o k e r 通過呼叫Co m m a n d物件的Ex e c u t e操作來提交一個請求。若該命令是可撤消的,Co n c r e t e C o m m a n d就在執行Ex c u t e操作之前儲存當前狀態以用於取消該命令。
•ConcreteCommand物件對呼叫它的Re c e i v e r的一些操作以執行該請求。

1.1.3        Java原始碼

接收者角色類

1.  public class Receiver {

2.      /**

3.       * 真正執行命令相應的操作

4.       */

5.      public void action(){

6.          System.out.println("執行操作");

7.      }

8.  }

抽象命令角色類

1.  public interface Command {

2.      /**

3.       * 執行方法

4.       */

5.      void execute();

6.  }

具體命令角色類

1.  public class ConcreteCommand implements Command {

2.      //持有相應的接收者物件

3.      private Receiver receiver = null;

4.      /**

5.       * 構造方法

6.       */

7.      publicConcreteCommand(Receiver receiver){

8.          this.receiver = receiver;

9.      }

10.    @Override

11.    public void execute() {

12.        //通常會轉調接收者物件的相應方法,讓接收者來真正執行功能

13.        receiver.action();

14.    }

15. 

16.}

請求者角色類

1.  public class Invoker {

2.      /**

3.       * 持有命令物件

4.       */

5.      private Command command = null;

6.      /**

7.       * 構造方法

8.       */

9.      public Invoker(Commandcommand){

10.        this.command = command;

11.    }

12.    /**

13.     * 行動方法

14.     */

15.    public void action(){

16.       

17.        command.execute();

18.    }

19.}

客戶端角色類

1.  public class Client {

2.   

3.      public static void main(String[] args) {

4.          //建立接收者

5.          Receiver receiver = new Receiver();

6.          //建立命令物件,設定它的接收者

7.          Command command = newConcreteCommand(receiver);

8.          //建立請求者,把命令物件設定進去

9.          Invoker invoker = new Invoker(command);

10.        //執行方法

11.        invoker.action();

12.    }

13. 

14.}