天天看點

指令模式

定義:請求以指令的形式包裹在對象中,并傳給調用對象。調用對象尋找可以處理該指令的合适的對象,并把該指令傳給相應的對象,該對象執行指令,對請 求排隊或者記錄請求日志,可以提供指令的撤銷和恢複功能

優點:1.調用者角色與接收者角色之間沒有任何依賴關系,松耦合。

           2.Command可像其他的對象一樣被操縱和擴充,可以增加和修改。可以裝配成組合指令

           3進而用戶端發出的請求可以在被處理之前都存放在Invoker類的容器中,可以在這個類中對請求排序,篩選,類似于aop

缺點:1.使用指令模式可能會導緻某些系統有過多的具體指令類。因為針對每一個指令都需要設計一個具體指令類,是以某些系統可能需要大量具體指令類,這将影響指令模式的使用

使用場景:1.在某些場合,比如要對行為進行"記錄、撤銷/重做、事務"等處理

                   2.隊列

引申:1.指令模式結合其他模式會更優秀:指令模式可以結合責任鍊模式,實作指令族解析任務;結合模闆方法模式,則可以減少 Command子類的膨脹問題。

類圖:

指令模式

Receiver 要執行的方法

代碼

Receiver類

1. class Receiver{
2. void auxiliary() {
3.         System.out.println("滾去輔助");
4.     }
5. void fightWild() {
6.         System.out.println("滾去打野");
7.     }
8. void hangUp() {
9.         System.out.println("滾去挂機");
10.     }
11. }      

Command (固定寫法)

1. public interface Command {
2. /**
3.      * @MethodName execute
4.      * @Descrition 指令執行。指令執行之前和之後可做自己想要的操作
5.      * @Param []
6.      * @return void
7.      */
8. void execute();
9. }      

ConcreteCommand(固定寫法 實作接口 去調用接受者的方法)

1. public class ConcreteCommandA implements Command{
2. 
3. private Receiver receiver;//持有行為執行者的引用
4. 
5. public ConcreteCommandA(Receiver receiver) {
6. this.receiver = receiver;
7.     }
8. 
9. @Override
10. public void execute() {
11.         receiver.auxiliary();
12.     }
13. }      
1. public class ConcreteCommandB implements Command{
2. 
3. private Receiver receiver;//持有行為執行者的引用
4. 
5. public ConcreteCommandB(Receiver receiver) {
6. this.receiver = receiver;
7.     }
8. 
9. @Override
10. public void execute() {
11.         receiver.fightWild();
12.     }
13. }      

Invoker(個人了解如同隊列 将Command臨時放入放入)

1. public class Invoker {
2. private Command command;//持有指令類的引用
3. 
4. public Invoker(Command command) {
5. this.command = command;
6.     }
7. 
8. //get set方法
9. 
10. /**
11.      * @MethodName toMakeIt
12.      * @Descrition 執行請求
13.      * @Param []
14.      * @return void
15.      */
16. public void toMakeIt(){
17.         command.execute();
18.     }
19. }      

調用

1. public class Client {
2. public static void main(String[] args) {
3. //生成隊列
4. Invoker  invoker = new Invoker();
5. Command commandA = new ConcreteCommandA(new Receiver())
6.         invoker.setCommand(commandA);
7.         invoker.toMakeIt();
8. Command commandB = new ConcreteCommandA(new Receiver())
9.         invoker.setCommand(commandB );
10.         invoker.toMakeIt();
11. 
12.     }
13. }      

繼續閱讀