Decorator Pattern allows new functionality to be added to an existing object without changing its structure. This type of design pattern belongs to the structural pattern, which is a package of existing classes.
This pattern creates a decorative class to wrap the original class and provides additional functionality while maintaining the integrity of the class method signature.
We demonstrate the use of decorator mode through the following example. Among them, we will decorate a shape with different colors without changing the shape class.
accomplish
We will create a Shape interface and an entity class that implements the Shape interface. Then we create an abstract decorative class ShapeDecorator that implements the Shape interface and use the Shape object as its instance variable.
RedShapeDecorator is an entity class that implements ShapeDecorator.
DecoratorPatternDemo, our demo class uses RedShapeDecorator to decorate Shape objects.
Step 1
Create an interface.
Shape.java
public interface Shape { void draw();}Step 2
Create an entity class that implements the interface.
Rectangle.java
public class Rectangle implements Shape { @Override public void draw() { System.out.println("Shape: Rectangle"); }}Circle.javapublic class Circle implements Shape { @Override public void draw() { System.out.println("Shape: Circle"); }}Step 3
Create an abstract decorative class that implements the Shape interface.
ShapeDecorator.java
public abstract class ShapeDecorator implements Shape { protected Shape decoratedShape; public ShapeDecorator(Shape decoratedShape){ this.decoratedShape = decoratedShape; } public void draw(){ decoratedShape.draw(); } }Step 4
Creates an entity decorative class that extends from the ShapeDecorator class.
RedShapeDecorator.java
public class RedShapeDecorator extends ShapeDecorator { public RedShapeDecorator(Shape decoratedShape) { super(decoratedShape); } @Override public void draw() { decoratedShape.draw(); setRedBorder(decoratedShape); } private void setRedBorder(Shape decoratedShape){ System.out.println("Border Color: Red"); }}Step 5
Use RedShapeDecorator to decorate Shape objects.
DecoratorPatternDemo.java
public class DecoratorPatternDemo { public static void main(String[] args) { Shape circle = new Circle(); Shape redCircle = new RedShapeDecorator(new Circle()); Shape redRectangle = new RedShapeDecorator(new Rectangle()); System.out.println("Circle with normal border"); circle.draw(); System.out.println("/nCircle of red border"); redCircle.draw(); System.out.println("/nRectangle of red border"); redRectangle.draw(); }}Step 6
Verify the output.
Circle with normal borderShape: CircleCircle of red borderShape: CircleBorder Color: RedRectangle of red borderShape: RectangleBorder Color: Red
Thank you for reading, I hope it can help you. Thank you for your support for this site!