The Decorator attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.Also called as Wrapper.
Problem
Sometimes we want to add responsibilities to individual objects (aTextView ) not to an entire class. ( i.e. how to give control to client to decorate the component with a border / a scroll bar )
Illustration:
Solution
- One way to add responsibilities is with inheritance.Inheriting a border with another class puts a border along very subclass instance ( inflexible solution ).
- A more flexible approach is to enclose the component in another objects that adds the border. The enclosing object is called Decorator.
- The Decorator confirm to interface of the component it decorate so that its presence is transparent to its components clients.
Applicability
Use Decorator
- To add responsibilities to individual objects dynamically and transparently, that is, without affecting other objects.
- For responsibilities that can be withdrawn.
- When extension by subclassing in impractical. Sometimes a large number of independent extensions are possible and would produce an explosion of subclasses to support every combination. Or a class definition may be hidden or otherwise unavailable for subclassing.
Structure
Collaborations
Decorator forwards requests to its Component object. It may optionally perform additional operations before and after forwarding the request.
Consequences
- More flexibility than static inheritance:
- to add or delete responsibilities to objects at runtime simply by attaching and detaching them.
- Providing different decorator classes for a specific component class lets you mix and match responsibilities.
- Avoids feature-laden classes high up in the hierarchy:
- Decorator offers a pay-as-you-go approach to adding responsibilities.Instead of trying to support all features in a complex, customizable class, you can define simple class and add functionality incrementally with Decorator objects.
- A decorator and its component aren’t identical:
- A decorator acts as a transparent enclosure.
- Lots of little objects :
- Decorator often results in system composed of lots of little objects that all look like, this may leed to maintenance nightmare and hard to learn.
Model
Related Patterns
Adapter: Adapter changes an object's interface, Decorator enhances an object's responsibilities. Decorator is thus more transparent to the client. As a consequence, Decorator supports recursive composition, which isn't possible with pure Adapters
Adapter provides a different interface to its subject. Proxy provides the same interface. Decorator provides an enhanced interface
Composite: A decorator can be viewed as a degenerate composite with only one component. However, a decorator adds additional responsibilities—it isn’t intended for object aggregation.
No comments:
Post a Comment