本文實例講述了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程序設計有所幫助。
新聞熱點
疑難解答
圖片精選