装饰模式实例与UML

<?php
abstract class Tile{
    abstract function getWealthFactor();
}

class Plains extends Tile{
    private $wealthfactor=2;
    function getWealthFactor(){
        return $this->wealthfactor;
    }
}

abstract class TileDecorator extends Tile{
    protected $tile;
    function __construct(Tile $tile){
        $this->tile = $tile;
    }
}

class DiamondDecorator extends TileDecorator{
    function getWealthFactor(){
        return $this->tile->getWealthFactor()+2;
    }
}

class PollutionDecorator extends TileDecorator{
    function getWealthFactor(){
        return $this->tile->getWealthFactor()-4;
    }
}

//客户端调用
$tile = new Plains();
echo $tile->getWealthFactor();  //输出2

$tile = new DiamondDecorator(new Plains());
echo $tile->getWealthFactor();  //输出4

$tile = new PollutionDecorator(new DiamondDecorator(new Plains()));
echo $tile->getWealthFactor();  //输出0
?>

    装饰模式比继承更加灵活

    装饰模式使用组合和委托而不是只是使用继承来解决功能的变化问题(组合优于继承的原则,因为不断继承,会让代码变得很庞大)。例如我们上面的客户端调用例子3,如果我们按照之前的老方法不断继承,我们需要创建一个类Diamond类,还要创建一个Pollution类,才可以达到我们既实现获得Diamond又获得Pollution的功能。如果我们采用装饰模式,就可以灵活的组合了。例如我们还可以创建一个SeaDecorator类,然后这样调用new PollutionDecorator(new SeaDecorator(new Plains())),也可以这样调用new DiamondDecorator(new SeaDecorator(new Plains())),依次类推,使用组合,犹豫继承,下面是它的UML图解:




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值