JavaRush/Java Blog/Random EN/Decorator design pattern with examples
Sbv239
Level 23

Decorator design pattern with examples

Published in the Random EN group
members
The decorator design pattern allows us to dynamically add functionality to an object without affecting the behavior of objects of the same class. It sounds a little confusing, but once you see the code everything will become clearer. Features - A decorator allows you to add functionality to an existing object without changing its structure, that is, the original class does not change - The decorator design pattern is a structural pattern that provides a wrapper for an existing class - Decorator classes are created that wrap the original class and provide additional functionality while preserving method signatures of the original class intact - The decorator design pattern is most often used to follow the single responsibility principle from SOLID, since we do not load the original class with additional responsibilities, but divide them into decorator classes - The decorator is structurally almost similar to the chain of responsibility pattern (chain of responsibility) The following key points must be taken into account - A decorator is useful for being able to modify the behavior of an object during runtime. This code is easy to maintain and extend. - The disadvantage of this pattern is that a large number of decorator objects of the same type are used - The decorator pattern is often used in Java IO classes (FileReader, BufferedReader, etc.) What we will do - Create an interface - Create concrete implementations of this interface - Create an abstract decorator, implementing this interface - Let's create a concrete decorator that inherits from an abstract decorator - Use a concrete decorator to "decorate" concrete implementations of the interface Implementation: We will create the Shape interface and concrete classes that implement this interface. Next, we'll create an abstract decorator class, ShapeDecorator, that implements the Shape interface and has a Shape object as a class field. Decorator design pattern with examples - 1 - Shape is the name of the interface - The Rectangle, Triangle and Circle classes will be concrete classes that implement the Shape interface - ShapeDecorator is an abstract decorator class that implements the same Shape interface - RedShapeDecorator is a concrete class that implements ShapeDecorator - Demo is a demo class in which we will use RedShapeDecorator to decorate Shape objects Step 1 : create the Shape interface
public interface Shape {
    void draw();
}
Step 2 : Let's create several implementations of this interface. In the example below there will only be a circle, but in fact we will create a couple more: a rectangle and a triangle.
public class Circle implements Shape{
    @Override
    public void draw() {
        System.out.println("Я круг!");
    }
}
Step 3 : Create an abstract decorator that implements the Shape interface
public abstract class ShapeDecorator implements Shape {

    protected Shape decoratedShape;

    //Конструктор, принимающий an object Shape
    public ShapeDecorator(Shape decoratedShape) {
        this.decoratedShape = decoratedShape;
    }

    public void draw() {
        decoratedShape.draw();
    }
}
Step 4 : create a concrete decorator class that inherits from the abstract class
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("Сообщение от RedShapeDecorator. Цвет границы: красный");
    }
}
Step 5 : Use RedShapeDecorator to Color Our Objects
public class Demo {
    public static void main(String[] args)
    {
        Shape circle = new Circle();
        Shape redCircle= new RedShapeDecorator(new Circle());
        Shape redRectangle= new RedShapeDecorator(new Rectangle());
        Shape redTriangle = new RedShapeDecorator(new Triangle());

        System.out.println("\nОбычный круг:");
        circle.draw();

        System.out.println("\nКруг с красной границей:");
        redCircle.draw();

        System.out.println("\nПрямоугольник с красной границей:");
        redRectangle.draw();

        System.out.println("\nТреугольник с красной границей:");
        redTriangle.draw();
    }
}
Step 6 : look at the console and rejoice
Обычный круг:
Я круг!

Круг с красной границей:
Я круг!
Сообщение от RedShapeDecorator. Цвет границы: красный

Прямоугольник с красной границей:
Я прямоугольник!
Сообщение от RedShapeDecorator. Цвет границы: красный

Треугольник с красной границей:
Я треугольник!
Сообщение от RedShapeDecorator. Цвет границы: красный
Having analyzed the decorator design pattern as an example, we can conclude that its use is justified in the following cases: - When we want to add, improve or possibly remove the behavior or state of an object - When we simply want to change the functionality of one specific object of a class and leave the rest no change Thank you! Repository with project files Based on an article from the site geeksforgeeks.org My blog for a beginner Java Dev
Comments
  • Popular
  • New
  • Old
You must be signed in to leave a comment
This page doesn't have any comments yet