Decorator Design
Pattern
Elements of Reusable Object-Oriented Software
Content
1. Design Patterns
2. Decorator Design Pattern
3. Example
I. Class Structure
II. Implementation
4. Conclusion
2
Design Pattern
3
Best practices Solutions to
general problems
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
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
Example
6
Window
Window with Vertical
Scrollbar
Window with Horizontal
Scrollbar
Window with Border
Window with Vertical and Horizontal Scrollbar
Window with Vertical and Horizontal Scrollbar and Border
Class Structure
7
<<interface>>
Window
+ draw()
<<class>>
MainWindow
+ draw()
<<interface>>
WindowDecorator
+ draw()
<<class>>
Border
<<class>>
Vertical SB
<<class>>
Horizontal SB
Implementation
8
Window appMainWindow = new BorderDecorator(
new HorizontalScrollBarDecorator(
new VerticalScrollBarDecorator(
new MainWindow( 80, 24 ))));
appMainWindow.draw();
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
Kanushka Gayan
SE intern @ Extrogene Software (Pvt) Ltd
kanushkanet@gmail.com
071 879 4546
Thank You!

Decorator Design Pattern

Editor's Notes

  • #2 https://sourcemaking.com/design_patterns/decorator
  • #5 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.
  • #7 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.
  • #8 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.