
Decorator pattern is used to add additional responsibility/ functionality to existing behaviour of an object without altering its original structure.
This pattern creates a decorator class which is wrapper to the existing class and provides additional functionality keeping class methods signature intact.
The decorator pattern uses composition providing a flexible alternative to subclassing. Subclassing adds behaviour at compile time, and the change affects all instances of the original class, however decorator provides additional behaviour at runtime for individual objects.
What we get as a result of this:
“Concrete implementations is decoupled from dynamic behaviours and responsibilities.”
UML Class Diagram :
Code Snippets
Step 1
Create an interface Shape.java
public interface Shape {
void draw();
}
Step 2
Create a class Square and Circle implementing Shape interface.
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Draw a Square Shape");
}
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Draw a Circle Shape ");
}
}
Step 3
Create abstract Decorator class ShapeDecorator implementing the Shape interface.
public abstract class ShapeDecorator implements Shape {
protected Shape shapeToBeDecorated;
public ShapeDecorator(Shape shapeToBeDecorated){
this. shapeToBeDecorated = shapeToBeDecorated;
}
...
...
public void draw(){
shapeToBeDecorated.draw();
}
}
Step 4
Create a class BlueShapeDecorator concrete decorator class extending the ShapeDecorator class.
public class BlueShapeDecorator extends ShapeDecorator {
//Pass the object to be decorated to the constructor
public BlueShapeDecorator(Shape shapeToBeDecorated) {
super(shapeToBeDecorated);
}
...
...
@Override
public void draw() {
ShapeToBeDecorated.draw();
setBlueBorderLine(shapeToBeDecorated);
}
//
private void setBlueBorderLine(Shape shapeToBeDecorated){
System.out.println("Add border Line to Blue Shape");
}
}
Step 5
Use the BlueShapeDecorator to decorate Shape objects in DecoratorPatternDemo.java
public class DecoratorPatternSample {
public static void main(String[] args) {
Shape circle = new Circle();
Shape blueCircle = new BlueShapeDecorator(new Circle());
Shape blueSquare = new BlueShapeDecorator(new Square());
...
...
System.out.println("Circle without border");
circle.draw();
...
System.out.println("Circle decorated with Blue border");
blueCircle.draw();
...
...
System.out.println (“Square decorated with Blue border ");
blueSquare.draw()
}
}
Thanks for reading this article. You may find the article on my Medium blog as well.