php 装饰模式

/*
装饰模式:英文(decorator pattern)又叫装饰者模式。装饰模式是在不必改变原类文件和使用继承的情况下,
动态的扩展一个对象的功能。
比继承更加灵活,功能定义如果完全依赖于继承体系,会导致类的数量和层次过多,代码不好控制而且产生重复。
 */

/**
 *区域类
 *@author li.yonghuan
 *@version 2014.01.15
 *
 */
abstract class Tile{
    /**
     *获取财富值
     */
    abstract function getWealthFactor();
}

/**
 *平原
 *@author li.yonghuan
 *@version 2014.01.15
 *
 */
class Plains extends Tile{
    /**
     *财富值
     *@var int
     */
    private $wealthfactor = 2;

    /**
     *获取财富值
     *
     */
    public function getWealthFactor(){
        return $this->wealthfactor;
    }
}

/**
 *区域装饰器
 *@author li.yonghuan
 *@version 2014.01.15
 */
abstract class TileDecorator extends Tile{
    /**
     *区域对象
     *@var Tile object
     */
    protected $tile;

    /**
     *构造方法
     *@param Tile $tile
     *
     */
    public function __construct( Tile $tile ){
       $this->tile = $tile; 
    }
}

/**
 *钻石地形装饰器
 *@author li.yonghuan
 *@version 2014.01.15
 */
class DiamondDecorator extends TileDecorator{

   /**
    *钻石地形财富值
    *
    */ 
    public function getWealthFactor(){
        return $this->tile->getWealthFactor()+2;
    }
}

/**
 *污染地形装饰器
 *@author li.yonghuan
 *@version 2014.01.15
 */
class PollutionDecorator extends TileDecorator{
    /**
     *污染地形财富值
     *
     */
    public function getWealthFactor(){
        return $this->tile->getWealthFactor()-4;
    }
}


//测试
$tile = new Plains();
echo $wealth = $tile->getWealthFactor();    //2

$diamond = new DiamondDecorator( new Plains() );
echo $wealth = $diamond->getWealthFactor();      //4

$pollution = new PollutionDecorator( new DiamondDecorator( new Plains() ) );
echo $pollution->getWealthFactor();         //0

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值