概念
将来自客户端的请求传入一个对象,从而使你可用不同的请求对客户进行参数化。用于“行为请求者”与“行为实现者”解耦,可实现二者之间的松耦合,以便适应变化。
角色
command(命令):在一个方法调用之上定义一个抽象;
concretecommand(具体的命令):一个操作的实现;
invoker(调用者):引用command实例作为它可用的操作。
代码
代码如下:
<?php
header('content-type:text/html;charset=uft-8');
/**
 * 命令模式
 */
/**
 * interface validator 命令接口
 */
interface command
{
    /**
     * 有任何参数的方法
     * @param mixed
     * @return boolean
     */
    public function isvalid($value);
}
/**
 * class morethanzerovalidator 具体命令
 */
class concretecommand implements command
{
    /**
     * 实现验证方法
     *
     * @param $value
     *
     * @return bool
     */
    public function isvalid($value)
    {
        // 大于0的数字
        return $value > 0;
    }
}
/**
 * class concretecommandtwo 具体命令2
 */
class concretecommandtwo implements command
{
    /**
     * 实现验证方法
     *
     * @param $value
     *
     * @return bool
     */
    public function isvalid($value)
    {
        // 能被2整除的数字
        return $value % 2 == 0;
    }
}
/**
 * class invoker 调用者
 */
class invoker
{
    protected $_rule;
    /**
     * 构造方法
     * 接收具体命令对象
     * invoker constructor.
     *
     * @param command $rule
     */
    public function __construct (command $rule)
    {
        $this->_rule = $rule;
    }
    public function process(array $numbers)
    {
        foreach ($numbers as $n) {
            if ($this->_rule->isvalid($n)) {
                echo $n, "\n";
            }
        }
    }
}
/**
 * class client 客户端
 */
class client {
    /**
     * 测试
     */
    public static function test()
    {
        $invoker = new invoker(new concretecommand());
        $invoker->process(array(-1,-4,-8,1, 10, 15, 20, 36, 48, 59,111));
        echo '<br>';
        $invoker = new invoker(new concretecommandtwo());
        $invoker->process(array(-1,-4,-8,1, 10, 15, 20, 36, 48, 59,111));
    }
}
// 执行测试
client::test();
运行结果:
1 10 15 20 36 48 59 111 
-4 -8 10 20 36 48
   
 
   