【设计模式】之装饰器模式(二)-PHP

本文通过一个具体案例介绍了装饰模式的应用,展示了如何通过组合和委托轻松地为对象增加职责,而不使用继承。文中定义了一系列类,包括地形抽象类、平原类、钻石地形类及污染地区类,演示了如何计算不同地形的价值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * 装饰模式范例及其描述
 * 主要是使用组合以及委托的形式来实现
 * 是对象能够轻松的组合
 * 以下是描述地形的一些类
 * 需求:输出地形区域的价值数值
 */

/**
 * 地形抽象类 提供一个获取地形区域值的接口
 * 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();  //常轻松的获得了受污染的藏有钻石的平原 价值

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

深入沟通_it6688668

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值