http://www.oodesign.com/decorator-pattern.html
前面一天是composite,所以今天就看decorator了。
下面这句话总结的很好:
想要扩展一个对象的功能,可以通过继承的方式静态(编译时)实现。然而有时必须在运行时动态的扩展一个对象的功能。
再提咖啡店的例子:咖啡店出售咖啡,或加了各种糖或调料的咖啡。我们需要在运行的时候,决定这是一个什么样的对象:pure coffee 或者是加了其他东西的咖啡。对于后者,就是一个在运行时加入了其他对象(糖)的对象。
- The intent of this pattern is to add additional responsibilities dynamically to an object
- Component - Interface for objects that can have responsibilities added to them dynamically.
- ConcreteComponent - Defines an object to which additional responsibilities can be added. 就相当于咖啡
- Decorator - Maintains a reference to a Component object and defines an interface that conforms to Component's interface. 相当于加了糖的咖啡,是一个复合对象。
- Concrete Decorators - Concrete Decorators extend the functionality of the component by adding state or adding behavior. 可以用于添加的各种对象,相当于糖,牛奶等。
Consequences
- Decoration is more convenient for adding functionalities to objects instead of entire classes at runtime. With decoration it is also possible to remove the added functionalities dynamically.
- Decoration adds functionality to objects at runtime which would make debugging system functionality harder.