设计模式——装饰模式

说明

装饰模式就是给一个对象增加一些新的功能,而且是动态的,要求装饰对象和被装饰对象实现同一个接口,装饰对象持有被装饰对象的实例。

示例

下面看下装饰模式的代码实现

//Source类是被装饰类,Decorator类是一个装饰类,可以为Source类动态的添加一些功能
interface Sourceable{
public function method();
}

class Source implements Sourceable{
public function method(){
echo "the original method!" . PHP_EOL;
}
}

class Decorator implements Sourceable{
private Sourceable $source;
public function __construct(Sourceable $source){
$this->source = $source;
}
public function method(){
echo "before decorator" . PHP_EOL;
$this->source->method();
echo "after decorator" . PHP_EOL;
}
}

//调用
$source = new Source();
$obj = new Decorator($source);
$obj->method();
/**
* output:
*
before decorator
the original method!
after decorator
*/

总结

装饰器模式的应用场景:
1、需要扩展一个类的功能。
2、动态的为一个对象增加功能,而且还能动态撤销。(继承不能做到这一点,继承的功能是静态的,不能动态增删。)
缺点:产生过多相似的对象,不易排错!


文章作者: Crazy Boy
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Crazy Boy !
赏

留言

想法、疑问或勘误,都可以写在这里。留言会公开显示。

正在准备留言区…