JAVA design pattern 8: Decoration mode, dynamically attach responsibilities to objects and extend the functionality of objects

Author's homepage : Designer Xiao Zheng
About the author : 3 years of JAVA full-stack development experience, focusing on JAVA technology, system customization, remote guidance, committed to enterprise digital transformation, CSDN blog expert, Alibaba Cloud community expert blogger, Blue Bridge cloud course instructor.

Insert image description here


1. What is decoration mode?

Decoration mode is a design mode and one of the structural modes.

In Java, the decorator pattern extends the functionality of an object by dynamically attaching responsibilities to it. It provides a more flexible way to extend the functionality of an object than inheritance.

In the decoration pattern, there is a base object (the decorated object) and a series of decorators (the decorating object).

The decorator and the base object implement the same interface, so they are interchangeable.

Decorators contain a reference to a base object and add new functionality to the base object.

Using the decoration mode, we can dynamically extend the functionality of the object at runtime without modifying the existing code\color{red}{Dynamicly extend the functionality of the object at runtime without modifying the existing code}Dynamically extend the object's functionality at runtime without modifying the existing code . It separates the object's behavior from the extension of the functionality,making the code more flexible and scalable.

The following is a simple Java code example. Please copy it to your local computer for execution.

// 定义口
public interface Shape {
    
    
    void draw();
}

// 实现接口的基础对象
public class Circle implements Shape {
    
    
    @Override
    public void draw() {
    
    
        System.out.println("画一个圆形");
    }
}

// 实现接口的装饰器
public abstract class ShapeDecorator implements Shape {
    
    
    protected Shape decoratedShape;

    ShapeDecorator(Shape decoratedShape) {
    
    
        this.decoratedShape = decoratedShape;
    }

    @Override
    public void draw() {
    
    
        decoratedShape.draw();
    }
}

// 具体的装饰器
public class RedShapeDecorator extends ShapeDecorator {
    
    
    public RedShapeDecorator(Shape decoratedShape) {
    
    
        super(decoratedShape);
    }

 @Override
    public void draw() {
    
    
        decoratedShape.draw();
        setRedBorder();
    }

    private void setRedBorder() {
    
    
        System.out.println("添加红色边框");
    }
}

// 使用示例
public class Main {
    
    
    public static void main(String[] args) {
    
    
        Shape circle = new Circle();

        // 使用装饰器功能扩展
        Shape redCircle = new RedShapeDecorator(new Circle());
        Shape redRectangle = new RedShapeDecorator(new Rectangle());

        circle.draw();          // 输出:画一个圆形
        redCircle.draw();       // 输出:画一个圆形,添加红色边框
        redRectangle.draw();    // 输出:画一个长方,添加红色边框
    }
}

In this case, Circleit's the base object, ShapeDecoratorit's the decorator, RedShapeDecoratorit's the concrete decorator.

Decorators can be used to add new functionality to a base object at runtime without modifying the base object's code.

Insert image description here


2. Decoration mode examples

The following is a simple example code of Java decoration mode. Please copy it to your local computer for execution.

// 定义接口
interface Shape {
    
    
    void draw();
}

// 实现接口的基础对象
class Circle implements Shape {
    
    
    @Override
    public void draw() {
    
    
        System.out.println("画一个圆形");
    }
}

// 实现接口的装饰器
abstract class ShapeDecorator implements Shape {
    
    
    protected Shape decoratedShape;

    public ShapeDecorator(Shape decoratedShape) {
    
    
        this.decoratedShape = decoratedShape;
    }

    @Override
    public void draw() {
    
    
        decoratedShape.draw();
    }
}

// 具体的装饰器
class RedShapeDecorator extends ShapeDecorator {
    
    
    public RedShapeDecorator(Shape decoratedShape) {
    
    
        super(decoratedShape);
    }

    @Override
    public void draw() {
    
    
        decoratedShape.draw();
        setRedBorder();
    }

    private void setRedBorder() {
    
    
        System.out.println("添加红色边框");
    }
}

// 使用示例
public class Main {
    
    
    public static void main(String[] args) {
    
    
        Shape circle = new Circle();

        // 使用装饰器功能扩展
        Shape redCircle = new RedShapeDecorator(new Circle());
        Shape redRectangle = new RedShapeDecorator(new Rectangle());

        circle.draw(); // 输出:画一个圆形
        redCircle.draw(); // 输出:画一个圆形,添加红色边框
        redRectangle.draw(); // 输出:画一个长方形,添加红色边框
    }
}

In this case, Circleit's the base object, ShapeDecoratorit's the decorator, RedShapeDecoratorit's the concrete decorator.

Use decorators to add new functionality to a base object at runtime without modifying the code of the base object itself.

An object's functionality can be dynamically extended by creating concrete decorators and passing in the base object.

Insert image description here


3. Application scenarios of decoration mode

Decorative modes are below 4 4It is used in 4 situations, please have a basic understanding.

  1. Dynamically add additional functionality to an object without affecting other objects.
  2. Existing objects need to be extended without changing the original code.
  3. Functional expansion needs to be achieved through composition rather than inheritance.
  4. The functionality of an object requires multiple extensions, and using inheritance can lead to explosive growth of classes.

Of course, the application scenarios of decoration mode include the following 4 4Category 4 , please study hard.

  1. IO stream operations : InputStream, OutputStream and other classes in Java are typical applications of decoration mode. Through the decorator mode, we can dynamically add new functions to the input and output streams at runtime, such as buffering, compression, etc., without modifying the original IO class.
  2. GUI components : In GUI applications, we often need to add additional decorations to components, such as borders, scroll bars, etc. Decoration mode allows us to dynamically add these decorations without changing the component class.
  3. Logging : Through the decoration mode, we can dynamically add new functions to the logger object, such as encryption, compression, etc., without modifying the original logger class.
  4. Database operation : In database operation, we can add additional functions to the database connection object through decoration mode, such as connection pool management, transaction management, etc.

In short, the decoration mode provides a flexible and reusable solution when it is necessary to dynamically add functionality to an object and extend the behavior of the object without changing the original code.

Insert image description here


4. Decorative mode interview questions

  1. Please explain what decorator mode is and give a concrete example.
  2. What is the difference between decorator pattern and inheritance?
  3. What are the advantages and disadvantages of decorative mode?
  4. What are the similarities and differences between decorator mode and adapter mode?
  5. When should I use decorator mode?
  6. How does the decoration mode dynamically add new functions to objects?
  7. What are the functions of component interface and decorator interface in decoration mode?
  8. In decorator mode, can there be multiple decorators? If so, how can I manage the order between multiple decorators?
  9. What is the difference between decorator mode and proxy mode?
  10. Does decoration mode violate the open-closed principle? Why?

Insert image description here

Guess you like

Origin blog.csdn.net/qq_41464123/article/details/132856973