Decorator design pattern in Java
The intent of the Decorator Design Pattern is to attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub-classing for extending functionality. The Decorator Pattern is used to extend the functionality of an object dynamically without having to change the original class source or using inheritance. This is accomplished by creating an object wrapper referred to as a Decorator around the actual object. The Decorator object is designed to ave the same interface as the underlying object. This allows a client object to interact with the Decorator object in exactly the same manner as it would with the underlying ctual object. The Decorator object contains a reference to the actual object. The Decorator object receives all requests (calls) from a client. In turn, it forwards these calls to the underlying object. The Decorator object adds some additional functionality before or after forwarding requests to the underlying object. This ensures that the additional functionality can be added to a given object externally at runtime without modifying its structure. We use inheritance or composition to extend the behavior of an object but this is done at compile time and it’s applicable to all the instances of the class. We can’t add any new functionality of remove any existing behavior at runtime – this is when Decorator pattern comes into picture.
When to use the Decorator Design Pattern:
Use the Decorator pattern in the following cases:
- To add responsibilities to individual objects dynamically and transparently, that is, without affecting other objects.
- For responsibilities that can be withdrawn.
- When extension by sub-classing is 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 sub-classing.
- It’s easy to maintain and extend when the number of choices are more.
Usage in Java:
- Decorator pattern is used a lot in Java IO classes, such as FileReader, BufferedReader etc.
- The disadvantage of decorator pattern is that it uses a lot of similar kind of objects (decorators).
Decorator UML class diagram
Source Decorator pattern - Wikipedia |
Comments
Post a Comment