Heim  >  Artikel  >  Backend-Entwicklung  >  PHP设计模式之命令模式

PHP设计模式之命令模式

高洛峰
高洛峰Original
2016-11-22 09:48:31861Durchsuche

概念

将来自客户端的请求传入一个对象,从而使你可用不同的请求对客户进行参数化。用于“行为请求者”与“行为实现者”解耦,可实现二者之间的松耦合,以便适应变化。

角色

Command(命令):在一个方法调用之上定义一个抽象;

ConcreteCommand(具体的命令):一个操作的实现;

Invoker(调用者):引用Command实例作为它可用的操作。

代码

代码如下:

<?php
header(&#39;Content-type:text/html;charset=uft-8&#39;);
/**
 * 命令模式
 */

/**
 * 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 &#39;<br>&#39;;
        $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


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:PHP压缩与归档—Bzip2Nächster Artikel:php基于命令行的扩展Readline