Decorator
英文简单描述
Intent
Attach additional responsibilities to an object dynamically.
Decorators provide a flexible alternative to subclassing for extending functionality.
How to
The decorator conforms to the interface of the component it decorates
so that its presence is transparent to the component's clients.
Component
defines the interface for objects that can have responsibilities added to them dynamically.
ConcreteComponent
defines an object to which additional responsibilities can be attached.
Decorator
maintains a reference to a Component object and defines an interface that conforms to Component's interface.
ConcreteDecorator
adds responsibilities to the component.
Known cases
Java IO Stream
GUI
UML
好处:
(1)比静态的继承更灵活 [More flexibility than static inheritance]
(2)保持组件轻量级 [Keeping Component classes lightweight]
(3)和策略区别:
A decorator lets you change the skin of an object; a strategy lets you change the guts. These are two alternative ways of changing an object.
代码: