PHP设计模式之命令模式

概念

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

角色

  • 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值