PHP設計模式之命令模式的深入解析_php技巧

來源:互聯網
上載者:User

命令模式(Command),命令模式是封裝一個通用操作的機制。

如果你熟悉C或PHP,你可能已經遇到過Command,它相當於程式中的:回調(callback)。回調通常使用一個函數指標或資料結構如PHP中的字串和數組實現,Command是在一個方法調用之上的抽象,它吸收了所有物件導向的好處:合成、繼承和處理。

例如,《設計模式》一書推薦使用Command儲存使用者行為鏈,以支援撤銷和重做操作。

注意PHP 5.3函數編程能力(閉包)可以被當做Command模式的一個本地實現,但為每一個命令階層使用抽象資料類型有助於型別安全。



在這個模式中,Invoker(調用者)知道傳遞給它的Command,無需依賴於真實的ConcreteCommand(具體的命令)實現,解決了通過配置進行方法調用相關的問題,如UI控制項按鈕和菜單等引用一個Command,它們的行為是通過通用的ConcreteCommand執行個體呈現的。
參與者:
◆Command(命令):在一個方法調用之上定義一個抽象;
◆ConcreteCommand(具體的命令):一個操作的實現;
◆Invoker(調用者):引用Command執行個體作為它可用的操作。
下面的代碼展示了Validator組件作為Command對象實現的樣本:
複製代碼 代碼如下:

/** 
 * The Command abstraction. 
 * In this case the implementation must return a result, 
 * sometimes it only has side effects. 
 */
interface Validator 

    /** 
     * The method could have any parameters. 
     * @param mixed 
     * @return boolean 
     */
    public function isValid($value); 


/** 
 * ConcreteCommand. 
 */
class MoreThanZeroValidator implements Validator 

    public function isValid($value) 
    { 
        return $value > 0; 
    } 


/** 
 * ConcreteCommand. 
 */
class EvenValidator implements Validator 

    public function isValid($value) 
    { 
        return $value % 2 == 0; 
    } 


/** 
 * The Invoker. An implementation could store more than one 
 * Validator if needed. 
 */
class ArrayProcessor 

    protected $_rule; 

    public function __construct (Validator $rule) 
    { 
        $this->_rule = $rule; 
    } 

    public function process(array $numbers) 
    { 
        foreach ($numbers as $n) { 
            if ($this->_rule->IsValid($n)) { 
                echo $n, "\n"; 
            } 
        } 
    } 


// Client code 
$processor = new ArrayProcessor(new EvenValidator()); 
$processor->process(array(1, 20, 18, 5, 0, 31, 42));

使用PHP設計模式中的命令模式的一些注意事項:
◆方法調用中的某些參數可以在構造ConcreteCommand時提供,有效地局部套用(currying)原始函數;
◆一個Command可以被看作是一個非常簡單的只有一個方法的策略(Strategy),重點放在對象的操作上;
◆ConcreteCommands也要組織它們需要的每一個資源,以實現它們的目標,主要是行為的Receiver(接受者),它們調用方法執行一個Command;
◆複合模式,裝飾模式和其它模式都可以和命令模式組合,獲得更多的Command,裝飾Command等等。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.