Decorator pattern comes under Structural design pattern.
Attach additional responsibilities to an object dynamically.
Decorators provide a flexible alternative to subclassing for extending functionality.
Behaviour & Advantages
Dynamically enhances the functionality of an object.
Supports dynamic functionality through wrapping.
Client may chain the dynamic features as needed at runtime.
Abstract interface for objects that can have responsibilities added to them dynamically.
An implementation of Component.
An implementation of Component which holds a reference to Concrete Component.
Concrete Decorator extends Decorator and enhances the functionality of Component.
This example shows a simple label which is decorated with various borders.
Here ILabel interface acts as Component and SimpleLabel class acts as Concrete Component.
Classes UpperCaseLabel, TopBorderedLabel and BottomBorderedLabel are Concrete Decorators
extended from Decorator class LabelDecorator.
We can see that label component is wrapped with Concrete Decorators in each step as a chain.
The output rendered changes as we wrap with each Concrete Decorator.
Decorator pattern usage is shown below,