2.8. 装饰模式(Decorator)
uml

代码实现
<?php
//装饰器要实现的接口
interface ContentInterface
{
    function display($str);
}
//具体装饰器 vpn替换成理智上网
class ReplaceVpn implements  ContentInterface {
    public function display($str)
    {
        return str_replace('vpn','理智上网',$str);
    }
}
//具体装饰器 脏话替换成***
class ReplaceDirtyLanguage implements  ContentInterface {
    public function display($str)
    {
        return str_replace('草泥马','***',$str);
    }
}
//执行者角色
Class ContentDecorator
{
    protected $decorators = [];
    public function addDecorator(ContentInterface $decorator)
    {
        $this->decorators[] = $decorator;
    }
    public function handleDecorator($str) //要被装饰的类
    {
        foreach ($this->decorators as $decorator)
            $str = $decorator->display($str);
        return $str;
    }
}
$str = '需要vpn才能看神兽草泥马';  //原本字符串
$decorator = new ContentDecorator();
$decorator->addDecorator(new ReplaceVpn());  //vpn装饰器
$decorator->addDecorator(new ReplaceDirtyLanguage());  //脏话装饰器
echo $decorator->handleDecorator($str);
需求变更
- 去掉 - 脏话的过滤:
 注释掉- $decorator->addDecorator(new ReplaceDirtyLanguage());即可
- 内容后面要加署名 
 创建一个署名具体装饰器,- $decorator->addDecorator(new 署名具体装饰器);
执行者
装饰器没有严格的规定,有些装饰器是 执行者 角色执行所有装饰器
(也就是ContentDecorator),而有些直接调用。
 
           php设计模式学习
php设计模式学习 
         
             
             关于 LearnKu
                关于 LearnKu
               
                     
                     
                     粤公网安备 44030502004330号
 粤公网安备 44030502004330号 
 
推荐文章: