【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>';

 

posted @ 2016-10-27 10:30  码农骆驼  阅读(242)  评论(0编辑  收藏  举报