PHP设计模式之装饰模式

本文知识来源于:《深入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>


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值