示例1:
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(); //$tile = new DiamondDecorator(new Plains()); //echo $tile->getWealthFactor(); $tile = new PollutionDecorator(new DiamondDecorator( new Plains() )); echo $tile->getWealthFactor();
示例2:
class RequestHelper{} //抽象基类 abstract class ProcessRequest{ abstract function process( RequestHelper $req ); } //具体组件 class MainProcess extends ProcessRequest{ function process( RequestHelper $req ){ echo __CLASS__."doing somthing useful with request<br />"; } } //抽象装饰类 //为子类保存了一个ProcessRequest对象 abstract class DecorateProcess extends ProcessRequest{ protected $processrequest; function __construct(ProcessRequest $pr){ $this->processrequest = $pr; } } class LogRequest extends DecorateProcess{ function process( RequestHelper $req){ echo __CLASS__.":logging request <br />"; $this->processrequest->process($req); } } class AuthenticateRequest extends DecorateProcess{ function process( RequestHelper $req){ echo __CLASS__.":authenticate request <br />"; $this->processrequest->process($req); } } class StrucureRequest extends DecorateProcess{ function process( RequestHelper $req){ echo __CLASS__.":strucure request <br />"; $this->processrequest->process($req); } } $process = new AuthenticateRequest(new StrucureRequest( new LogRequest ( new MainProcess()))); $process->process( new RequestHelper()); //AuthenticateRequest:authenticate request //StrucureRequest:strucure request //LogRequest:logging request //MainProcessdoing somthing useful with request