Decorator Pattern
Decorator Pattern
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.
We are demonstrating the use of decorator pattern via following example in which
we will decorate a shape with some color without alter shape class.
Implementation
We're going to create a Shape interface and concrete classes implementing the
Shape interface. We will then create an abstract decorator class ShapeDecorator
implementing the Shape interface and having Shape object as its instance variable.
Step 1
https://www.tutorialspoint.com/design_pattern/decorator_pattern.htm 1/4
15/01/24, 11:50 Design Patterns - Decorator Pattern
Create an interface.
Shape.java
Step 2
Create concrete classes implementing the same interface.
Rectangle.java
@Override
public void draw() {
System.out.println("Shape: Rectangle");
}
}
Circle.java
@Override
public void draw() {
System.out.println("Shape: Circle");
}
}
Step 3
Create abstract decorator class implementing the Shape interface.
ShapeDecorator.java
https://www.tutorialspoint.com/design_pattern/decorator_pattern.htm 2/4
15/01/24, 11:50 Design Patterns - Decorator Pattern
Step 4
Create concrete decorator class extending the ShapeDecorator class.
RedShapeDecorator.java
@Override
public void draw() {
decoratedShape.draw();
setRedBorder(decoratedShape);
}
Step 5
Use the RedShapeDecorator to decorate Shape objects.
DecoratorPatternDemo.java
https://www.tutorialspoint.com/design_pattern/decorator_pattern.htm 3/4
15/01/24, 11:50 Design Patterns - Decorator Pattern
Step 6
Verify the output.
https://www.tutorialspoint.com/design_pattern/decorator_pattern.htm 4/4