在這個模式中,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 } }
/** * 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"; } } } }