/**
* 装饰模式范例及其描述
* 主要是使用组合以及委托的形式来实现
* 是对象能够轻松的组合
* 以下是描述地形的一些类
* 需求:输出地形区域的价值数值
*/
/**
* 地形抽象类 提供一个获取地形区域值的接口
* Class Tile
*/
abstract class Tile{
abstract function getWealthFactor();
}
/**
* 平原类
* Class Plains
*/
class Plains extends Tile{
private $wealthFactor = 2; //平原地形的区域价值
public function getWealthFactor(){
return $this->wealthFactor;
}
}
/**
* 地形描述类 (装饰模式的重点类就在这里 这个类继承自地形基类 并不实现基类接口,只是一个委托类)
* Class TileDecorator
*/
abstract class TileDecorator extends Tile
{
protected $tile; //保存一个Tile实例
public function __construct(Tile $tile){
$this->tile = $tile;
}
}
/**
* 钻石地形继承自地形描述抽象类
* Class Diamond
*/
class DiamondDecorator extends TileDecorator{
public function getWealthFactor(){
return $this->tile->getWealthFactor()+2;
}
}
/**
* 污染地区
* Class PollutionDecorator
*/
class PollutionDecorator extends TileDecorator{
public function getWealthFactor(){
return $this->tile->getWealthFactor()-4;
}
}
// 客户端调用代码
$tile = new Plains();
echo $tile->getWealthFactor(); //获取了平原地形 输出价值2
echo '<hr />';
$tileOne = new DiamondDecorator($tile);
echo $tileOne->getWealthFactor(); //非常轻松的获得了有钻石的平原 价值
echo '<hr />';
$tileTwo = new PollutionDecorator($tile);
echo $tileTwo->getWealthFactor(); //常轻松的获得了受污染的平原 价值
echo '<hr />';
$tileThree = new PollutionDecorator($tileOne);
echo $tileThree->getWealthFactor(); //常轻松的获得了受污染的藏有钻石的平原 价值
【设计模式】之装饰器模式(二)-PHP
最新推荐文章于 2025-05-14 09:44:02 发布