<?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燕十八 面向对象与设计模式