php 设计模式之 责任链



1. 责任链模式

责任链模式,属于对象行为型的设计模式

使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系

将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止


2. 实列

abstract class FilterChain {
    protected $next;
    public function setNext($next) {
        $this->next = $next;
    }
    abstract public function filter($message);
}

class FilterStrict extends FilterChain {    // 链条
    public function filter($message) {
        foreach (['枪X', '弹X', '毒X'] as $v) {
            if (strpos($message, $v) !== false) {
                throw new \Exception('该信息包含敏感词汇!');
            }
        }
        if ($this->next) {
            return $this->next->filter($message);
        } else {
            return $message;
        }
    }
}

class FilterMobile extends FilterChain {    // 链条
    public function filter($message) {
        $message = preg_replace("/(1[3|5|7|8]\d)\d{4}(\d{4})/i", "$1****$2", $message);
        if ($this->next) {
            return $this->next->filter($message);
        } else {
            return $message;
        }
    }
}

$f1 = new FilterStrict();   // 链条
$f2 = new FilterMobile();   // 链条

$f1->setNext($f2);

$m1 = "现在开始测试链条1:语句中不包含敏感词,需要替换掉打架这种词,然后给手机号加上星:13333333333,这样的数据才可以对外展示哦";
echo $f1->filter($m1);

3. 使用场景

  1. if-else分支判断场景
  2. 根据不同等级发放优惠券
  3. 字符串一层一层过滤
  4. 请假审批
posted @ 2020-12-30 13:27  linsonga  阅读(67)  评论(0)    收藏  举报