裝飾模式指的是在不必改變原類文件和使用繼承的情況下,動態地擴展一個對象的功能。它是通過創建一個包裝對象,也就是裝飾來包裹真實的對象。
日常開發裝飾模式具體的應用場景?
比如文章編輯難題:
<?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();