Decorator Pattern

来源:互联网 发布:中科院院士 知乎 编辑:程序博客网 时间:2024/06/05 16:49

一块区域,它可能是平原/大山等等,如果该区域有钻石,它的财富值将增加;如果它被环境污染了,它的财富值将减少。并且它可能存在多情况的组合,要计算这样区域的财富值使用装饰模式很合适。

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(),'<br>';

$tile = new DiamondDecorator(new Plains());
echo $tile->getWealthFactor(),'<br>';
$tile = new PollutionDecorator(new DiamondDecorator(new Plains()));
echo $tile->getWealthFactor(),'<br>';


以下情况使用Decorator模式
1. 需要扩展一个类的功能,或给一个类添加附加职责。
2. 需要动态的给一个对象添加功能,这些功能可以再动态的撤销。
3. 需要增加由一些基本功能的排列组合而产生的非常大量的功能,从而使继承关系变的不现实。
4. 当不能采用生成子类的方法进行扩充时。一种情况是,可能有大量独立的扩展,为支持每一种组合将产生大量的子类,使得子类数目呈爆炸性增长。另一种情况可能是因为类定义被隐藏,或类定义不能用于生成子类。

参考http://baike.baidu.com/link?url=oqDA25Rzumaq7bqkfr0dxJy9c4B9p6AHNen9Z5Tokv5K8_n0qhbwpcbgc9wpc8xuxuW5HuOFB89TxW8JcvIZT_

0 0