Decorator mode of design mode

Posted by KDesigns on Wed, 15 Sep 2021 05:21:31 +0200

Most office workers have the habit of sleeping in. They are very nervous at work every morning, so many people will solve the breakfast problem in a convenient way in order to get more sleep. Some people may have pancakes for breakfast. They can add eggs or sausages to the pancakes, but no matter how "overweight", they are still a pancake. In real life, it is often necessary to add new functions to existing products or beautify their appearance, such as house decoration, photos and photo frames, which are all decorator modes.

In the process of software development, sometimes you want to use some existing components. These components may only perform some core functions. However, without changing its structure, its function can be expanded dynamically. All of these can be implemented in decorator mode.

Definition and characteristics of decorator mode

definition

It refers to the mode of dynamically adding some responsibilities (i.e. adding additional functions) to the object without changing the existing object structure. It belongs to the object structure mode.

advantage

  • Decorator is a powerful supplement to inheritance. It is more flexible than inheritance. It dynamically extends the function of an object without changing the original object, plug and play
  • Different effects can be achieved by using different decorative classes and the arrangement and combination of these decorative classes
  • The decorator mode is fully observed Opening and closing principle

shortcoming

  • Decorator pattern will add many subclasses, and overuse will increase the complexity of the program.

Structure and implementation of decorator mode

Usually, the function of extending a class is implemented by inheritance. However, inheritance has static characteristics, high coupling, and subclasses will expand with the increase of extended functions. The goal of decorator pattern is to create a wrapper object (i.e. decoration object) to wrap the real object and provide it with additional functions on the premise of keeping the class structure of the real object unchanged. The basic structure and implementation method are analyzed below.

Pattern structure

Decorator mode mainly includes the following roles.

  1. Abstract Component role: define an abstract interface to standardize objects ready to receive additional responsibilities.
  2. Concrete component role: implement abstract components and add some responsibilities to them by decorating roles.
  3. Abstract Decorator role: inherits abstract components and contains instances of specific components. You can extend the functions of specific components through its subclasses.
  4. Concrete decorator role: implement relevant methods of abstract decoration and add additional responsibilities to specific component objects.

Structure diagram of decorator mode

:

Implementation of pattern

The implementation code of decorator mode is as follows:

package decorator;
public class DecoratorPattern {
    public static void main(String[] args) {
        Component p = new ConcreteComponent();
        p.operation();
        System.out.println("---------------------------------");
        Component d = new ConcreteDecorator(p);
        d.operation();
    }
}
//Abstract component role
interface Component {
    public void operation();
}
//Specific component role
class ConcreteComponent implements Component {
    public ConcreteComponent() {
        System.out.println("Create concrete component roles");
    }
    public void operation() {
        System.out.println("Calling methods for specific component roles operation()");
    }
}
//Abstract decorative role
class Decorator implements Component {
    private Component component;
    public Decorator(Component component) {
        this.component = component;
    }
    public void operation() {
        component.operation();
    }
}
//Specific decorative role
class ConcreteDecorator extends Decorator {
    public ConcreteDecorator(Component component) {
        super(component);
    }
    public void operation() {
        super.operation();
        addedFunction();
    }
    public void addedFunction() {
        System.out.println("Add additional functions to specific component roles addedFunction()");
    }
}

The results are as follows:

Create concrete component roles
 Calling methods for specific component roles operation()
---------------------------------
Calling methods for specific component roles operation()
Add additional functions to specific component roles addedFunction()

Application scenario of decorator mode

The structure and characteristics of the decorator mode were explained earlier. The applicable application scenarios are introduced below. The decorator mode is usually used in the following situations.

  • When you need to add additional responsibilities to an existing class, but you can't expand it by generating subclasses. For example, if the class is hidden, or the class is the ultimate class, or inheritance will produce a large number of subclasses.
  • When it is necessary to arrange and combine a set of existing basic functions to produce a lot of functions, it is difficult to realize it by using inheritance relationship, but it is easy to realize it by using decorator mode.
  • When the functional requirements of an object can be added or revoked dynamically.

The most famous application of decorator pattern in Java language is the design of Java I/O standard library. For example, the subclass FilterInputStream of InputStream, the subclass FilterOutputStream of OutputStream, the subclass BufferedReader and FilterReader of Reader, and the subclass BufferedWriter, FilterWriter and PrintWriter of Writer are abstract decoration classes.

"Decoration mode" and“ proxy pattern ”What's the difference?

Both extend the methods of the class, but the decorator pattern emphasizes enhancing itself. After being decorated, you can use the enhanced functions on the enhanced class. After enhancement, you are still you, but your ability is stronger; The agent mode emphasizes that you should let others help you do some responsibilities that have little to do with your business (logging, setting cache). The proxy mode is to control the object, because the proxy object is often difficult to obtain directly or its interior does not want to be exposed.
The decorator mode should provide enhancements to the decorated object, while the proxy mode controls the use of the proxy object and does not provide enhancements to the object itself.

Topics: Design Pattern