PHP設計模式之 裝飾模式

不言
發布: 2023-03-24 10:06:02
原創
1194 人瀏覽過

這篇文章介紹的內容是關於PHP設計模式之裝飾模式,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下

裝飾模式(Decorator) 屬於結構型模式之一,定義:動態地為一個物件增加一些額外的職責。

 在我們生活中最為普遍的例子就是在玩遊戲的時候隨時伴隨著人物角色的裝備,皮膚。我相信不管男生女生,玩遊戲的都買過吧。

 其中最常見的就是一些遊戲開發商,透過去做一些裝備,例如武器,衣服,鞋子,戒指等等,來吸引玩家購買,穿在身上不僅好看,還帶有額外屬性。

 這個例子是典型裝飾器模式的應用,特點是在不影響其他類別的情況下動態添加其它具體裝備類別

<?php  
           
/** 构件接口类      
 *  interface IComponent          
 */     
interface IComponent  
{  
    function Display();  
}  
  
/** 人物类     
 *  Person         
 */    
Class Person implements IComponent  
{  
    private $name;  
  
    function __construct($name)  
    {  
        $this->name = $name;  
    }  
  
    function Display()  
    {  
        echo "{$this->name}当前装备:";  
    }  
  
}  
  
/** 装备类    
 *  Equipment         
 */   
Class Equipment implements IComponent  
{  
    protected $component;  
  
    function Decorator(IComponent $component)  
    {  
        // 动态添加  
        $this->component = $component;  
    }  
  
    function Display()  
    {  
        if(!empty($this->component)){  
            $this->component->Display();  
        }  
    }     
}  
  
  
/** 具体装备 武器类    
 *  Weapon        
 */   
Class Weapon extends Equipment  
{  
    function Display(){  
        parent::Display();  
        echo "龙泉剑 ";  
    }  
}  
  
/** 具体装备 戒指类    
 *  Ring        
 */   
Class Ring extends Equipment  
{  
    function Display(){  
        parent::Display();  
        echo "复活戒指 ";  
    }  
}  
  
/** 具体装备 鞋子类    
 *  Shoes       
 */   
Class Shoes extends Equipment  
{  
    function Display(){  
        parent::Display();  
        echo "御风履 ";  
    }  
}  
  
// 如果需要可以继续添加具体的装备 腰带 裤子 手镯
登入後複製
<?php  
  
// 装饰器模式 index.php  
header("Content-Type:text/html;charset=utf-8");  
require_once "Decorator.php";  
  
// 创建人物  
$people = new Person("战士");  
  
// 武器  
$Weapon = new Weapon();  
// 戒指  
$Ring = new Ring();  
// 鞋子  
$Shoes = new Shoes();  
  
// 动态添加函数  
$Weapon->Decorator($people);  
$Ring->Decorator($Weapon);  
$Shoes->Decorator($Ring);  
  
// 显示  
$Shoes->Display();
登入後複製



#輸出結果:


#
战士当前装备:龙泉剑 复活戒指 御风履
登入後複製

相關推薦:

# PHP設計模式之組合模式

PHP設計模式之橋接模式

PHP設計模式之適配器模式

以上是PHP設計模式之 裝飾模式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!