将所有功能建立在继承体系上会导致系统中的类爆炸式的增多。更糟糕的是当你尝试继承数上不同的分支做相似的修改时,代码会产生重复。
装饰模式是解决此类问题很好的办法。代码如下
bstract 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){
$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();
$Plains->getWealthFactor; //2
$tile = new diamondDecorator(new Plains());
$tile->getWealthFactor();//4
$tile = new pollutionDecorator(new diamondDecorator(new Plains()))
$tile->getWealthFactor();//0
若不用装饰模式,那么则既有污染又有钻石的情况又需要增加一个新类来继承。
若如代码所示,加一个区域装饰器tileDecorator,代码就可以灵活组合,降低耦合。需要的类大大减少,组建系统也更加的灵活。可以更容易的增加若干新的装饰器来满足各种复杂的情况。