I am going over my design patterns, and one pattern I have yet to seriously use in my coding is the Decorator Pattern.
I understand the pattern, but what I would love to know are some good concrete examples of times in the real world that the decorator pattern is the best/optimal/elegant solution. Specific situations where the need for the decorator pattern is really handy.
Thanks.
The Decorator pattern is best when the decorators modify the behavior of the methods in the interface. A decorator can add methods, but added methods don't carry through when you wrap in another decorator.
Example. The Decorator attaches additional responsibilities to an object dynamically. The ornaments that are added to pine or fir trees are examples of Decorators. Lights, garland, candy canes, glass ornaments, etc., can be added to a tree to give it a festive look.
Advantage of Decorator PatternIt enhances the extensibility of the object, because changes are made by coding new classes. It simplifies the coding by allowing you to develop a series of functionality from targeted classes instead of coding all of the behavior into the object.
Decorator pattern allows a user to add new functionality to an existing object without altering its structure. This type of design pattern comes under structural pattern as this pattern acts as a wrapper to existing class.
The Decorator
Pattern is used for adding additional functionality to an existing object
(i.e. already instantiated class at runtime), as opposed to object's class
and/or subclass. It is easy to add functionality to an entire class of objects by subclassing an object's class, but it is impossible to extend a single object this way. With the Decorator Pattern, you can add functionality to a single object and leave others like it unmodified.
In Java, a classical example of the decorator pattern is the Java I/O Streams implementation.
FileReader frdr = new FileReader(filename); LineNumberReader lrdr = new LineNumberReader(frdr);
The preceding code creates a reader -- lrdr
-- that reads from a file and tracks line numbers. Line 1 creates a file reader (frdr
), and line 2 adds line-number tracking.
Actually, I'd highly encourage you to look at the Java source code for the Java I/O classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With