初识PHP设计模式--装饰模式

 装饰模式(Decorator)属于结构型模式之一,定义:动态地给一个对象增加一些额外的职责。

 在我们生活中最为普遍的例子就是在玩游戏的时候随时伴随着人物角色的装备,皮肤。我相信不管男生女生,玩游戏的都买过吧。

 其中最常见的就是一些游戏开发商,通过去做一些装备,例如武器,衣服,鞋子,戒指等等,来吸引玩家购买,穿在身上不仅好看,还带有额外属性。

 这个例子是典型装饰器模式的应用,特点是在不影响其他类的情况下动态添加其它具体装备类。

<?php
/**        
 * Created by Sublime.        
 * User: Ryan        
 * Date: 2018/1/24        
 * File: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();
输出结果:

战士当前装备:龙泉剑 复活戒指 御风履 


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值