命令模式(Command),命令模式是封裝一個(gè)通用操作的機(jī)制。
如果你熟悉C或PHP,你可能已經(jīng)遇到過Command,它相當(dāng)于程序中的:回調(diào)(callback)。回調(diào)通常使用一個(gè)函數(shù)指針或數(shù)據(jù)結(jié)構(gòu)如PHP中的字符串和數(shù)組實(shí)現(xiàn),Command是在一個(gè)方法調(diào)用之上的抽象,它吸收了所有面向?qū)ο蟮暮锰帲汉铣伞⒗^承和處理。
例如,《設(shè)計(jì)模式》一書推薦使用Command存儲(chǔ)用戶行為鏈,以支持撤銷和重做操作。
注意PHP 5.3函數(shù)編程能力(閉包)可以被當(dāng)做Command模式的一個(gè)本地實(shí)現(xiàn),但為每一個(gè)命令層次結(jié)構(gòu)使用抽象數(shù)據(jù)類型有助于類型安全。
復(fù)制代碼 代碼如下:
/**
* 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));
新聞熱點(diǎn)
疑難解答