使用情景:假如一本书的上市,要经过创作,编辑加上摘要,SEO人员给书加上SEO关键词这么一个有序的过程,通过继承的方式的确可以做到有序地对文章装饰不同的东西,但是这样的纵深继承结构不太科学,所以从线上结构转换成一个父类多个子类的两层结构。
// 原始文章类 class Article { protected $_content; protected $_parent; public function __construct($content) { $this->_content = $content; } public function decorate() { return $this->_content; } } // 编辑给文章装饰上摘要的类 class BianAticle extends Article { public function __construct($parent) { $this->_parent = $parent; $this->decorate(); } public function decorate() { return $this->_parent->decorate() . ‘<br>摘要:ABCD‘; } } // SEO人员给文章加上SEO class SEOArticle extends Article { public function __construct($parent) { $this->_parent = $parent; } public function decorate() { return $this->_parent->decorate() . ‘<br>SEO:EFGH‘; } } $bian = new BianAticle(new SEOArticle(new Article(‘文章A‘))); echo $bian->decorate(); echo ‘<br>‘; echo ‘--------------------------------------------------‘; echo ‘<br>‘; $seo = new SEOArticle(new BianAticle(new Article(‘文章B‘))); echo $seo->decorate();
结果:
文章A SEO:EFGH 摘要:ABCD -------------------------------------------------- 文章B 摘要:ABCD SEO:EFGH