装饰器模式

  内容来自《深入PHP面向对象、模式与实践》

  装饰器模式其实和他的名称是一个意思,就是起“装饰的作用”。

  要想起到装饰作用,首先必须有一个原型,这个原型就是要被装饰的对象,这个原型包含一些自身的属性。执行装饰动作的是另外一个对象,目的就是修改原型中的某些属性,让他看起来和以前不一样,因为做了装饰了嘛,但是,原型本身还是没有变,只是装饰之后的返回的样子变了。所以思路就是:一个将原型传递给装饰者,装饰者对原型进行装饰,然后返回经过装饰后的对象。

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

//这就是原型对象,被装饰的对象
class Plains extends Tile{
    //原型中有一个wealthfactor属性,其他装饰器都是装饰这个属性
    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;
    }
}

$plains = new Plains();
echo $plains->getWealthFactor()."
";
//输出2

//将一个原型对象传给一个钻石装饰者,让其进行装饰
$tile = new DiamondDecorator( new Plains() );
echo $tile->getWealthFactor()."
";
//输出4

//进行多次的装饰
$tile = new PollutionDecorator( new DiamondDecorator( new Plains() ) );
echo $tile->getWealthFactor()."
";
//输出0
?>

  

  

原文地址:https://www.cnblogs.com/-beyond/p/8760414.html