您的位置:首页 > 编程语言 > PHP开发

php 装饰模式

2014-03-02 14:08 417 查看
/*
装饰模式:英文(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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: