>  기사  >  백엔드 개발  >  PHP 디자인 패턴 명령 패턴

PHP 디자인 패턴 명령 패턴

高洛峰
高洛峰원래의
2016-11-22 09:48:31862검색

개념

클라이언트의 요청을 객체에 전달하여 다양한 요청으로 클라이언트를 매개변수화할 수 있습니다. 변경 사항에 적응하기 위해 "동작 요청자"와 "동작 구현자"를 분리하여 둘 사이의 느슨한 결합을 달성하는 데 사용됩니다.

역할

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


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.