• 【PHP设计模式 09_ZhuangShiQi.php】装饰器模式 (decorator)


    <?php 
    /**
     * 【装饰器模式 (decorator)】
     * 有时候发布一篇文章需要经过很多人手,层层处理
     */
    
    header("Content-type: text/html; charset=utf-8");
    
    /************************ 《装饰器模式 实现》 ************************/
    //文章基础类
    class BaseWz{
        protected $content; //定义文章内容属性
        protected $art=null; //定义一个文章对象
        public function __construct($content){
            $this->content = $content;
        }
        public function decorator(){
            return $this->content;
        }
        
    }
    
    //1.小编添加摘要,继承原始的文章类
    class XiaobianWz extends BaseWz{
        public function __construct(BaseWz $art){
            $this->art = $art;
        }
        public function decorator(){
            //调用父类的decorator方法,就可以把父类的content返回
            //$res = parent::decorator().'【新增摘要from小编】';
            //$res = $this->art->content.='【新增摘要from小编】';
            $res = $this->content = $this->art->decorator().'【新增摘要from小编】';
            return $res;
        }
    }
    
    //2.SEO人员添加优化信息
    class SEOWz extends BaseWz{
        public function __construct(BaseWz $art){
            $this->art = $art;
        }
        public function decorator(){
            $res = $this->content = $this->art->decorator().'【新增优化信息from SEOer】';
            return $res;
        }
    }
    
    //3.广告部添加广告信息
    class ADWz extends BaseWz{
        public function __construct(BaseWz $art){
            $this->art = $art;
        }
        public function decorator(){
            $res = $this->content = $this->art->decorator().'【新增广告信息from ADer】';
            return $res;
        }
    }
    
    //4. 后面可以任意添加...
    
    /*开始调用*/
    $content = "这就是一篇简单的文章";
    
    $base_wz = new BaseWz($content); //这里传进去的$content是 文章内容
    echo $base_wz->decorator();
    echo '<br>----------------------------------------<br>';
    
    $xb_wz = new XiaobianWz($base_wz); //这里传进去的 $base_wz 是上面的 “基础文章对象”
    echo $xb_wz->decorator();
    echo '<br>----------------------------------------<br>';
    
    $seo_wz = new SEOWz($xb_wz); //这里传进去的 $xb_wz 是上面的 “小编文章对象”
    echo $seo_wz->decorator();
    echo '<br>----------------------------------------<br>';
    
    $ad_wz = new ADWz($seo_wz); //这里传进去的 $seo_wz 是上面的 “SEO文章对象”
    echo $ad_wz->decorator();
    echo '<br>----------------------------------------<br>';
  • 相关阅读:
    多表查询
    mysql记录的增删改和单表查询
    作业45
    修改表 复制表
    多表关联
    约束
    关于服务器raid的一个记录
    安装linux操作系统--浪潮服务器
    关于python中的__new__方法
    关于类的总结之二
  • 原文地址:https://www.cnblogs.com/rxbook/p/6002994.html
Copyright © 2020-2023  润新知