引言php
组合模式帮组咱们聚合组件,装饰模式则使用相似节后来帮组咱们改变具体组件的功能this
问题spa
将全部功能简历在集成体系上会致使系统中的类“爆炸式”增多,当你尝试对集成书上不一样的分支作想死的修改是,代码可能会产生重复ssr
uml图日志
代码实现code
<?php /* decoration.php 装饰模式 */ class Requesthelper{} //抽象基类 abstract class ProcessRequest{ abstract function process(Requesthelper $req); } //具体的组件 class MainProcess extends ProcessRequest{ function process(Requesthelper $req){ print __CLASS__.": doing something useful with request<br>"; } } //抽象装饰类 abstract class DecorateProcess extends ProcessRequest{//继承 protected $processrequest; function __construct(ProcessRequest $pr){//组合 $this->processrequest = $pr; } } //日志装饰类 class LogRequest extends DecorateProcess{ function process(Requesthelper $req){ print __CLASS__.": logging request<br>"; $this->processrequest->process($req);//委托 } } //认证装饰类 class AuthenticateRequest extends DecorateProcess{ function process(Requesthelper $req){ print __CLASS__.": authenticating request<br>"; $this->processrequest->process($req); } } //认证装饰类 class StructreRequest extends DecorateProcess{ function process(Requesthelper $req){ print __CLASS__.": structring request<br>"; $this->processrequest->process($req); } } //client $process = new AuthenticateRequest(new StructreRequest(new LogRequest(new MainProcess()))); $process ->process(new Requesthelper()); ?>
效果对象
组合和继承一般都是同时使用的,所以logrequest是继承自processrequest,可是却保险为对另一个processrequest对象的封装blog
由于修饰对象做为子对象的包装,因此保持基类中的方法尽量少是很重要的继承