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.
4. Decorator Design Pattern
• Attach additional responsibilities to an object dynamically.
• Decorators provide a flexible alternative to subclassing for
extending functionality.
• Wrapping a gift, putting it in a box, and wrapping the box.
4
5. Problem
You want to add behavior or state to individual objects at runtime.
Inheritance is not feasible because it is static and applies to an
entire class.
5
8. Implementation
8
Window appMainWindow = new BorderDecorator(
new HorizontalScrollBarDecorator(
new VerticalScrollBarDecorator(
new MainWindow( 80, 24 ))));
appMainWindow.draw();
9. Conclusion
• Decorators allow behavior modification at runtime rather than
going back into existing code and making changes
• The decorator pattern supports the principle that classes should
be open for extension but closed for modification
9
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.
This pattern creates a decorator class which wraps the original class and provides additional functionality keeping class methods signature intact.
Suppose you are working on a user interface toolkit and you wish to support adding borders and scroll bars to windows. You could define an inheritance hierarchy like
But the Decorator pattern suggests giving the client the ability to specify whatever combination of "features" is desired.
Suppose you are working on a user interface toolkit and you wish to support adding borders and scroll bars to windows. You could define an inheritance hierarchy like
But the Decorator pattern suggests giving the client the ability to specify whatever combination of "features" is desired.