聲明:本系列博客參考資料《大話設計模式》,作者程傑。
裝飾器模式又叫裝飾者模式。裝飾模式是在不必改變原類文件和使用繼承的情況下,動態地擴展一個對象的功能。它是通過創建一個包裝對象,也就是裝飾來包裹真實的對象。
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. 當不能採用生成子類的方法進行擴充時。一種情況是,可能有大量獨立的擴展,爲支持每一種組合將產生大量的子類,使得子類數目呈爆炸性增長。另一種情況可能是因爲類定義被隱藏,或類定義不能用於生成子類。