PHP设计模式之装饰模式
2015-08-19 15:33
579 查看
本文知识来源于:《深入PHP面向对象、模式和实践》一书
问题:
如果出现一个即被污染也含钻石的土地,
要去计算它的财富价值,
那么我们是否应该去创建多一个类呢?
答案:
不需要,我们完全可以利用装饰模式,
组合两个已有的独立类成为一个组合类,
将计算财富价值的方法做稍微的改动
<?php /* Title:装饰模式 Detail:平原、污染、钻石对象的独立和组合。 */ abstract class Tile{ abstract function getWealthFactor(); } //平原类,wealthfactor为财富值 class Plains extends Tile{ private $wealthfactor=2; function getWealthFactor(){ return $this->wealthfactor; } } //含钻石土地类 class DiamondPlains extends Plains{ function getWealthFactor(){ return parent::getWealthFactor()+2; } } //污染土地类 class PollutedPlains extends Plains{ function getWealthFactor(){ return parent::getWealthFactor()-4; } } //以上的类的实现,我们可以轻松获得每个类型的土地的财富价值
问题:
如果出现一个即被污染也含钻石的土地,
要去计算它的财富价值,
那么我们是否应该去创建多一个类呢?
答案:
不需要,我们完全可以利用装饰模式,
组合两个已有的独立类成为一个组合类,
将计算财富价值的方法做稍微的改动
<?php abstract class Tile{ abstract function getWealthFactor(); } //平原类,wealthfactor为财富值 class Plains extends Tile{ private $wealthfactor=2; function getWealthFactor(){ return $this->wealthfactor; } } //含钻石土地类 class DiamondPlains extends Plains{ protected $tile; function __construct(Tile $tile){ $this->tile=$tile; } function getWealthFactor(){ return parent::getWealthFactor()+2+$this->tile->getWealthFactor(); } } //污染土地类 class PollutedPlains extends Plains{ protected $tile; function __construct(Tile $tile){ $this->tile=$tile; } function getWealthFactor(){ return parent::getWealthFactor()-4+$this->tile->getWealthFactor(); } } //净化土地类 class PurePlains extends Plains{ protected $tile; function __construct(Tile $tile){ $this->tile=$tile; } function getWealthFactor(){ return parent::getWealthFactor()+4+$this->tile->getWealthFactor(); } } //创建一个污染含钻石的净化土地类 $tile=new DiamondPlains(new PollutedPlains(new PurePlains())); echo $tile->getWealthFactor();</span>
相关文章推荐
- PHP生命周期
- php基础语法
- 绘图: matplotlib核心剖析
- crontab 不能开启,且报错`/var/run.bak/crond.pid': Input/output error
- PHP设计模式之组合模式
- ThinkPHP自动验证分析
- root用户可以通过phpmyadmin登录,普通用户却不行,提示1045的错误
- ftp
- Mac下安装from matplotlib import pyplot或者 import matplotlib.pyplot as plt报错
- Yii 验证和消息
- iis7.5中使用fastcgi方式配置php5.6.5
- 解析PayPal支付接口的PHP开发方式
- PHPStorm单词拼写纠正提示设置
- zend framework分析总结[转]
- laravel route
- 4步win7下简单FTP服务器搭建
- PHP引号转义中解决POST,GET,Mysql数据自动转义问题
- PHP冒泡排序法
- PHP 问题汇总
- PHP编译less文件-lessphp的使用