1. 程式人生 > 其它 >設計模式專題(十九) ——命令模式

設計模式專題(十九) ——命令模式

設計模式專題(十九)——命令模式

(原創內容,轉載請註明來源,謝謝)

一、概念

命令模式(Command)將一個請求封裝為一個物件,從而可用不同的請求對客戶進行引數化;對請求排隊或記錄請求日誌,以支援可撤銷的操作。

該模式可以用來設計訊息佇列,可以按需求將命令記入日誌,也允許請求方撤回請求。另外,新的命令不影響舊的類。該模式實現解耦,將請求的操作與實際的操作分開。

1、優點

1)解除了請求者與實現者之間的耦合,降低了系統的耦合度。

2)對請求排隊或記錄請求日誌,支援撤銷操作。

2、缺點

命令模式需要為每一種具體的命令設計一個類,這樣如果命令太多的情況下,結果是類會太多。

二、類圖

三、設計方案

命令模式主要有三種角色類——需求者(客戶端)、命令發起者、命令執行者,其中需求者將需求發給命令發起者,由命令發起者作為中間類,協調多個需求者以及多個命令執行者之間的關係。

類似餐廳的點菜,需求者就是消費者,命令發起者是服務員,命令執行者是廚師。但是這裡的命令發起者只有一個,以確保按照需求的先後順序,去要求命令執行者執行命令。

命令模式共需要4個角色,invoker、command、concretecommand、receiver,分別是分發命令類、命令虛類、具體命令類、命令接收類。

1)Command:

//1:命令通用虛類
abstract class Command{
         protected$receiver;
         publicfunction __construct(Receiver $receiver){
                   $this->receiver= $receiver;
         }
         publicfunction execute(){}
}

2)ConcreteCommand:

//2:具體命令執行類
class ConcreteCommand extends Command{
         function__construct(Receiver $receiver){
                   parent::__construct($receiver);
         }
         publicfunction execute(){
                   $this->receiver->action();
         }
}

3)Invoker

//3:發動命令類
class Invoker{
         private$command;
         publicfunction __construct(Command $command){
                   $this->command= $command;
         }
         publicfunction setCommand(Command $command){
                   $this->command= $command;
         }
         publicfunction executeCommand(){
                   $this->command->execute();
         }
}

4)Receiver

//4:命令接收者類
class Receiver{
         publicfunction action(){
                   echo'執行請求';
         }
}

5)客戶端

$r = new Receiver();
$c = new ConcreteCommand($r);
$i = new Invoker($c);
$i->executeCommand();

——written by linhxx 2017.08.27

相關閱讀:

設計模式專題(十八) ——橋接模式

設計模式專題(十七) ——單例模式

設計模式專題(十六)——迭代器模式

設計模式專題(十五) ——組合模式

設計模式專題(十四)——介面卡模式

設計模式專題(十三) ——備忘錄模式

設計模式專題(十二)——狀態模式

設計模式專題(十一)——抽象工廠模式

設計模式專題(十)——觀察者模式

設計模式專題(九) ——外觀模式

設計模式專題(八) ——模板方法模式

設計模式專題(七)——建造者模式

設計模式專題(六)——原型模式

設計模式專題(五)——工廠方法模式

設計模式專題(四)——代理模式

設計模式專題(三)——裝飾模式

設計模式專題(二)——策略模式

設計模式專題(一)——面向物件的設計原則