简介

装璜器模式能够在指标对象原有的根底上,增加其余性能,实现动静加强。

须要明确的是代理模式也有相似的作用,而装璜器模式与代理模式最大的不同在于,装璜器模式下,对指标对象设置加强的权力交给了 client,即 client 先要失去指标对象,之后决定要用哪些装璜器给指标对象加强,一层层嵌套。

具体来说比方 Java 的 IO 操作,个别须要先 new 一个指标对象 FileInputStream,之后将其作为参数传给 BufferedInputStream 即可实现有 buffer 加强性能 InputStream。

装璜器类和被装璜类应该实现同一接口,这样能够保障被装璜器加强后的类的调用形式与之前始终,且反对有限次装璜调用。

装璜器是典型的组合优于继承的例子,试想如果用继承来实现加强的话,每有一个加强项,都须要重写一个类,而反对多种加强项的类则须要继承屡次。

角色

  • Component 接口

    定义根本的操作

  • Decorator 装璜器

    实现 Component 接口,加强代码所在

  • Wrappee/Concrete Component 被装璜的原始类

    实现 Component 接口,是被装璜加强的原始类

类图

图中所示,Component 是共有的接口,Concrete Component 是被装璜的类,Concrete Decorators 装璜器类。装璜器类接管 Component 为参数,execute 办法即加强办法。

代码

interface Component{    public function operation(): string;}class ConcreteComponent implements Component{    public function operation(): string    {        return "ConcreteComponent";    }}class Decorator implements Component{    protected $component;    public function __construct(Component $component)    {        $this->component = $component;    }    public function operation(): string    {        return $this->component->operation();    }}class ConcreteDecoratorA extends Decorator{    public function operation(): string    {        return "ConcreteDecoratorA(" . parent::operation() . ")";    }}class ConcreteDecoratorB extends Decorator{    public function operation(): string    {        return "ConcreteDecoratorB(" . parent::operation() . ")";    }}function clientCode(Component $component){    echo "RESULT: " . $component->operation() . "\n";}$simple = new ConcreteComponent();echo "Client: I've got a simple component:\n";clientCode($simple);echo "\n";$decorator1 = new ConcreteDecoratorA($simple);$decorator2 = new ConcreteDecoratorB($decorator1);echo "Client: Now I've got a decorated component:\n";clientCode($decorator2);

output:

Client: I've got a simple component:RESULT: ConcreteComponentClient: Now I've got a decorated component:RESULT: ConcreteDecoratorB(ConcreteDecoratorA(ConcreteComponent))

本文由mdnice多平台公布