Home > Backend Development > PHP Tutorial > PHP design pattern command pattern

PHP design pattern command pattern

高洛峰
Release: 2016-11-22 09:48:31
Original
924 people have browsed it

Concept

Pass the request from the client into an object, allowing you to parameterize the client with different requests. Used to decouple "behavior requester" and "behavior implementer" to achieve loose coupling between the two in order to adapt to changes.

Role

Command (command): defines an abstraction on top of a method call;

ConcreteCommand (concrete command): the implementation of an operation;

Invoker (caller): refers to the Command instance as its available operations .

Code

The code is as follows:

<?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();
Copy after login

Running result:

1 10 15 20 36 48 59 111 
-4 -8 10 20 36 48
Copy after login


Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template