装饰模式(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();
输出结果:
战士当前装备:龙泉剑 复活戒指 御风履