装饰模式指的是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。
日常开发装饰模式具体的应用场景?
比如文章编辑难题:
<?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 BianArticle extends Article{
public function summary(){
return $this->content.'小编加了摘要';
}
}
$art = new BianArticle('好好学习');
echo $art->summary();
//又请了SEO,要对文章做description处理
class SeoArticle extends BianArticle{
}
如上在编辑文章的过程中可能需要不停的增加各种功能,然后就需要增加类并继承之前的类来实现,这样做明显是不合理的,类之间耦合性高,扩展起来极不方便,那怎么解决这个问题呢?
这里可以使用装饰模式
php实现代码如下:
<?php
/*
装饰模式实现文章编辑
*/
class BaseArt{
protected $content;
protected $art;
public function __construct($content){
$this->content = $content;
}
public function decoration(){
return $this->content;
}
}
//编辑文章摘要
class BianArt extends BaseArt{
public function __construct($art){
$this->art = $art;
$this->decoration();
}
public function decoration(){
return $this->content = $this->art->decoration().'小编加了摘要';
}
}
//SEO添加关键词
class SEOArt extends BaseArt{
public function __construct($art){
$this->art = $art;
$this->decoration();
}
public function decoration(){
return $this->content = $this->art->decoration().'SEO添加关键词';
}
}
$art = new BaseArt('天天向上');
$Bian = new BianArt($art);
$Seo = new SEOArt($Bian);
echo $Seo->decoration();