This is the 15th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

An overview of the

The Decorator Pattern dynamically adds some additional responsibilities to an object and is more flexible than subclassing in terms of adding functionality to the object.

Decorator mode can add additional new behavior to an object without changing its own functionality. For example, Zhang SAN can add a whistle to the kettle to make it serve as a reminder.

structure

● Component (Abstract Component) : It is the common parent of the concrete Component and the abstract decorator class and declares the business methods implemented in the concrete Component. Its introduction enables clients to handle undecorated and decorated objects in a consistent manner.

● ConcreteComponent: this is a subclass of the abstract component class that defines ConcreteComponent objects, implements methods declared in the abstract component, and decorators can add additional responsibilities to it.

● Decorator: It is also a subclass of the abstract component class and is used to add responsibilities to the concrete component, but the responsibilities are implemented in its subclass. It maintains a reference to an abstract component object that calls the method that decorates the previous component object and extends that method through its subclasses for decorating purposes.

● ConcreteDecorator: This is a subclass of the Abstract decorator class that adds new responsibilities to components. Each concrete decorator class defines some new behavior, it can call the methods defined in the abstract decorator class, and it can add new methods to extend the behavior of the object.

advantages

  1. The decorator class and the decorator class can develop independently without coupling each other, in line with the open and closed principle.
  2. Decoration pattern is an alternative to inheritance, which solves the problems of class expansion and strong intrusion caused by inheritance.
  3. Decorator patterns can dynamically extend the functionality of an implementation class.

disadvantages

The function of the implementation class is decorated with multiple decoration classes, which will make the system more complex and increase the coupling degree of the implementation class.

Application scenarios

  1. You need to extend the functionality of a class or add additional functionality to a class.
  2. You need to add functions to an object dynamically, and those functions can be undone dynamically.
  3. You need to modify and add functionality for a number of sibling classes.

Applications in the JDK

The decorator pattern is used in java.io.InputStream in the JDK. Java. IO. InputStream is abstract artifacts, Java. IO. FileInputStream is concrete component, Java. IO. FilterInputStream is abstract decoration, Java.io.DataInputStream is the concrete decoration.