zoukankan      html  css  js  c++  java
  • 【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>';
  • 相关阅读:
    求素数(定义法,埃式法,欧拉法)
    打表法
    python学习日记(匿名函数)
    python学习日记(编码再回顾)
    python学习日记(文件操作练习题)
    python学习日记(迭代器、生成器)-乱七八糟
    python学习日记(生成器函数进阶)
    python学习日记(装饰器的补充)
    python学习日记(函数--装饰器)
    python学习日记(函数进阶)
  • 原文地址:https://www.cnblogs.com/rxbook/p/6002994.html
Copyright © 2011-2022 走看看