Blogger Information
Blog 11
fans 0
comment 0
visits 6637
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP设计模式学习笔记——装饰器模式
青Blue的博客
Original
576 people have browsed it

实例

<?php
/**
* @Description: 装饰器模式
* @Author: luoxiaojin
* @Date: 2020-06-29 21:24:29
* @LastEditors: luoxiaojin
* @LastEditTime: 2020-06-29 22:07:35
* @FilePath: \design_patterns\l8.php
*/

// 以发布文章为例

class Article{
    protected $content;

    public function __construct($content){
        $this->content = $content;
    }

    public function decorator(){
        return $this->content;
    }
}

// $art = new Article('好好学习,天天向上');
// echo $art->decorator();

class EditorArticle extends Article{
    public function summary(){
        return $this->content . '小编加了摘要';
    }
}

// $art = new EditorArticle('好好学习,天天向上');
// echo $art->summary();

class SEOArticle extends EditorArticle{
    public function seo(){
        $this->content = parent::summary($this->content);
        return $this->content.'SEO';
    }
}

// $art = new SEOArticle('好好学习,天天向上');
// echo $art->seo();

// 以上为继承实现,嵌套层级随着业务复杂,嵌套过深
///////////////////////////////////////////////////////////
// 以下为策略模式实现

class BaseArticle{
    protected $content;
    protected $atr;

    public function __construct($content){
        $this->content = $content;
    }

    public function decorator(){
        return $this->content;
    }
}

class AddArticle extends BaseArticle{
    public function __construct(BaseArticle $atr){
        $this->art = $atr->decorator();
        $this->decorator();
    }
    public function decorator(){
        return $this->art .= '小编加了摘要。';
    }
}

class AdArticle extends BaseArticle{
    public function __construct(BaseArticle $atr){
        $this->art = $atr->decorator();
    }
    public function decorator(){
        return $this->content .= '加了广告.';
    }
}


echo (new AddArticle(new AdArticle(new BaseArticle('好好学习,天天向上。'))))->decorator();

运行实例 »

点击 "运行实例" 按钮查看在线实例

——学习参考与 bilibili燕十八 面向对象与设计模式

Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post