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
相关文章推荐
- php 组合模式
- php 命令模式
- Vsftp设置为PASV mode(被动模式传送)
- Vsftp设置为PASV mode(被动模式传送)
- php 对象适配器模式
- php 适配器模式
- php 抽象工厂模式
- php 工厂模式
- [开心学PHP100天(七)]精讲PHP构造函数:父亲和儿子的恩恩怨怨
- PureFtp+PureAdmin:实现基于虚拟账号的FTP服务器
- 成为一个PHP专家:缺失的环节
- 最新 tp的逆向
- wowza配置rtsp/rtp播放
- php时间戳与date格式转换
- php接口和抽象类使用示例详解
- php通过字符串调用函数示例
- PHP 遍历数组的方法汇总
- php持久登录、记住我功能实现
- PHP 函数call_user_func和call_user_func_array用法详解
- PHP 字符串长度判断效率更高的方法