Decorator
Decorator
Motivation:
A graphical user interface toolkit, for example, should let you add properties like borders or
One way to add responsibilities is with inheritance. Inheriting a border from another class
A client can't control how and when to decorate the component with a border.
A more flexible approach is to enclose the component in another object that adds the border.
The decorator conforms to the interface of the component it decorates so that its presence is
The decorator forwards requests to the component and may perform additional actions (such
as drawing a border) before or after forwarding. Transparency lets you nest decorators
For example, suppose we have a TextView object that displays text in a window.
TextView has no scroll bars by default, because we might not always need them. When we
Applicability:
Use Decorator
• to add responsibilities to individual objects dynamically and transparently, that is,without affecting other
objects.
• when extension by subclassing is impractical. Sometimes a large number of independent extensions are
possible and would produce an explosion of subclasses to support every combination.
Structure:
Participants
• Component (VisualComponent)
- defines the interface for objects that can have responsibilities added to them dynamically.
• ConcreteComponent (TextView)
- defines an object towhich additional responsibilities canbe attached.
• Decorator
- maintains a reference to a Component object and defines an interface that conforms to
Component's interface.
• ConcreteDecorator (BorderDecorator, ScrollDecorator)
- adds responsibilities to the component.