本文知识来源于:《深入PHP面向对象、模式和实践》一书
<?php
/*
Title:装饰模式
Detail:平原、污染、钻石对象的独立和组合。
*/
abstract class Tile{
abstract function getWealthFactor();
}
//平原类,wealthfactor为财富值
class Plains extends Tile{
private $wealthfactor=2;
function getWealthFactor(){
return $this->wealthfactor;
}
}
//含钻石土地类
class DiamondPlains extends Plains{
function getWealthFactor(){
return parent::getWealthFactor()+2;
}
}
//污染土地类
class PollutedPlains extends Plains{
function getWealthFactor(){
return parent::getWealthFactor()-4;
}
}
//以上的类的实现,我们可以轻松获得每个类型的土地的财富价值
问题:
如果出现一个即被污染也含钻石的土地,
要去计算它的财富价值,
那么我们是否应该去创建多一个类呢?
答案:
不需要,我们完全可以利用装饰模式,
组合两个已有的独立类成为一个组合类,
将计算财富价值的方法做稍微的改动
<?php
abstract class Tile{
abstract function getWealthFactor();
}
//平原类,wealthfactor为财富值
class Plains extends Tile{
private $wealthfactor=2;
function getWealthFactor(){
return $this->wealthfactor;
}
}
//含钻石土地类
class DiamondPlains extends Plains{
protected $tile;
function __construct(Tile $tile){
$this->tile=$tile;
}
function getWealthFactor(){
return parent::getWealthFactor()+2+$this->tile->getWealthFactor();
}
}
//污染土地类
class PollutedPlains extends Plains{
protected $tile;
function __construct(Tile $tile){
$this->tile=$tile;
}
function getWealthFactor(){
return parent::getWealthFactor()-4+$this->tile->getWealthFactor();
}
}
//净化土地类
class PurePlains extends Plains{
protected $tile;
function __construct(Tile $tile){
$this->tile=$tile;
}
function getWealthFactor(){
return parent::getWealthFactor()+4+$this->tile->getWealthFactor();
}
}
//创建一个污染含钻石的净化土地类
$tile=new DiamondPlains(new PollutedPlains(new PurePlains()));
echo $tile->getWealthFactor();</span>