Re: [模式] 装饰者模式(decorator)只有一种结构吗?

楼主: FTM (....)   2013-01-14 17:15:32
或许回归到 Decorator Pattern 的 Intent 来看会较清楚
Intent of Decorator (from GoF Book):
Attach additional responsibility to an object dynamically.
Decorators provide a flexible alternative to subclassing for
extending functionality.
由上得知, 使用 Decortor 所欲表达物件关系/行为是:
* 系统中有一种特殊的 Object, 姑且称之为 Component
* Component 常常有额外附加 responsibility 的需要
* 额外附加 responsibility 的动作需要能动态给定
(因此直接 subclassing 并不适宜)
有了以上理解后, 再回头看看 Decorator 结构上的两个重点
1. Decorator decorates (as an aggregation) a Component
Decorator 包装了 component, 透过这层包装
Decorator 可在正式将责任交付给 component 之前(或之后)
额外进行所欲附加的行为
2. Decorator is a Component
为了确保 Client 仍可正常使用 "包装" 后的 Component
Decorator 必须也符合 Component 所制定的 Interface
这可透过 Inheritance 达成 (Decorator extends Component)

Links booklink

Contact Us: admin [ a t ] ucptt.com