大话设计模式-装饰器模式

27 阅读1分钟

题目:写一个可以给人搭配不同服饰的系统。比如QQ、论坛都有的Avatar系统。

分析:被装饰的目标:人。 装饰物: 不同的服饰。

  1. 目标不知道有装饰系统的存在,装饰系统通过扩展目标,来对目标增加新的装饰;
  2. 装饰物可以组合:如帽子、上衣、裤子的组合;

类图:

decorator.webp

题目实现:

Component 和 ConcreteComponent: Component_ConcreteComponent.png

Decorator_ConcreteDecorators: Decorator_ConcreteDecorators.png

decoratorTest: decoratorTest.png

总结: Decorator 装饰抽象类,继承自Component,但对于Component来说,无需知道Decorator是否存在。 通过具体的ConcreteDecorator就可以装饰原来的Component对象了,从而起到添加职责的能力。

在Decorator中使用SetComponent 来对Component进行包装,从而形成一个装饰链条。