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.
Participants
Component
Abstract interface for objects that can have responsibilities added to them dynamically.
Concrete Component
An implementation of Component.
Decorator
An implementation of Component which holds a reference to Concrete Component.
Concrete Decorator
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,
//Label step by step chaining
ILabel label = new SimpleLabel("be the coder");
label.print();
System.out.println();
label = new UpperCaseLabel(label);
label.print();
System.out.println();
label = new TopBorderedLabel(label);
label.print();
System.out.println();
label = new BottomBorderedLabel(label);
label.print();
//Label direct chaining
System.out.println();
label = new TopBorderedLabel( new BottomBorderedLabel( new SimpleLabel("Decorator Pattern")));
label.print();
}
}
It gives the following output,
be the coder
BE THE CODER
************
BE THE CODER
************
BE THE CODER
************
*****************
Decorator Pattern
*****************