本文實例講述了PHP設計模式之裝飾器模式。分享給大家供大家參考,具體如下:
裝飾器模式又叫裝飾者模式。裝飾模式是在不必改變原類文件和使用繼承的情況下,動態地擴展一個對象的功能。它是通過創建一個包裝對象,也就是裝飾來包裹真實的對象。
UML類圖:

角色:
組件對象的接口:可以給這些對象動態的添加職責
所有裝飾器的父類:需要定義一個與組件接口一致的接口,并持有一個Component對象,該對象其實就是被裝飾的對象。
具體的裝飾器類:實現具體要向被裝飾對象添加的功能。用來裝飾具體的組件對象或者另外一個具體的裝飾器對象。
具體代碼:
?php
/**
* Created by PhpStorm.
* User: Jiang
* Date: 2015/5/3
* Time: 11:11
*/
/**組件對象接口
* Interface IComponent
*/
interface IComponent
{
function Display();
}
/**待裝飾對象
* Class Person
*/
class Person implements IComponent
{
private $name;
function __construct($name)
{
$this->name=$name;
}
function Display()
{
echo "裝扮的:{$this->name}br/>";
}
}
/**所有裝飾器父類
* Class Clothes
*/
class Clothes implements IComponent
{
protected $component;
function Decorate(IComponent $component)
{
$this->component=$component;
}
function Display()
{
if(!empty($this->component))
{
$this->component->Display();
}
}
}
//------------------------------具體裝飾器----------------
class PiXie extends Clothes
{
function Display()
{
echo "皮鞋 ";
parent::Display();
}
}
class QiuXie extends Clothes
{
function Display()
{
echo "球鞋 ";
parent::Display();
}
}
class Tshirt extends Clothes
{
function Display()
{
echo "T恤 ";
parent::Display();
}
}
class Waitao extends Clothes
{
function Display()
{
echo "外套 ";
parent::Display();
}
}
調用客戶端測試代碼:
header("Content-Type:text/html;charset=utf-8");
//------------------------裝飾器模式測試代碼------------------
require_once "./Decorator/Decorator.php";
$Yaoming=new Person("姚明");
$aTai=new Person("A泰斯特");
$pixie=new PiXie();
$waitao=new Waitao();
$pixie->Decorate($Yaoming);
$waitao->Decorate($pixie);
$waitao->Display();
echo "hr/>";
$qiuxie=new QiuXie();
$tshirt=new Tshirt();
$qiuxie->Decorate($aTai);
$tshirt->Decorate($qiuxie);
$tshirt->Display();
適用場景:
1. 需要動態的給一個對象添加功能,這些功能可以再動態的撤銷。
2. 需要增加由一些基本功能的排列組合而產生的非常大量的功能,從而使繼承關系變的不現實。
3. 當不能采用生成子類的方法進行擴充時。一種情況是,可能有大量獨立的擴展,為支持每一種組合將產生大量的子類,使得子類數目呈爆炸性增長。另一種情況可能是因為類定義被隱藏,或類定義不能用于生成子類。
更多關于PHP相關內容感興趣的讀者可查看本站專題:《php面向對象程序設計入門教程》、《PHP基本語法入門教程》、《PHP數組(Array)操作技巧大全》、《php字符串(string)用法總結》、《php+mysql數據庫操作入門教程》及《php常見數據庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。
您可能感興趣的文章:- 學習php設計模式 php實現裝飾器模式(decorator)
- PHP設計模式之裝飾器模式定義與用法詳解
- PHP簡單裝飾器模式實現與用法示例
- PHP設計模式之裝飾器模式定義與用法簡單示例
- PHP設計模式(七)組合模式Composite實例詳解【結構型】
- PHP設計模式(六)橋連模式Bridge實例詳解【結構型】
- PHP設計模式(五)適配器模式Adapter實例詳解【結構型】
- PHP設計模式(四)原型模式Prototype實例詳解【創建型】
- PHP設計模式(三)建造者模式Builder實例詳解【創建型】
- PHP設計模式(一)工廠模式Factory實例詳解【創建型】
- PHP設計模式概論【概念、分類、原則等】
- PHP設計模式(八)裝飾器模式Decorator實例詳解【結構型】