Original: Curly brace MC(wechat official account: Huakuohao-MC), welcome to share, please keep the source.

Decorator mode is primarily used to add additional functionality without changing the structure of classes and objects. The main idea is to define a decorator class that includes the original class and provides additional functionality.

For example

Suppose you have a graphics class that can draw a corresponding graphic pattern. If you want to add color to your graphics without changing the original graphics class, you can consider using decorator mode.

Let’s start with the UML class diagram:

Let’s look at the code implementation logic.

Graphic interface, realize drawing function.

public interface Shape {
    void draw(a);
}
Copy the code

A Circle class implements a Circle

public class Circle implements Shape {
    @Override
    public void draw(a) {
        System.out.println("Shape: Circle"); }}Copy the code

Define a graphic decorator class to achieve coloring function, first define an abstract base decorator class, this decorator class will contain the original class, its subclass to achieve concrete color coloring.

public abstract class ShapeDecorator implements Shape {

    // Reference the shap class
    protected Shape decoratedShape;

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

    @Override
    public void draw(a) { decoratedShape.draw(); }}Copy the code

The concrete shader subclass RedShapeDecorator implements concrete shaders.

public class RedShapeDecorator extends ShapeDecorator {
    public RedShapeDecorator(Shape decoratedShape) {
        super(decoratedShape);
    }
    @Override
    public void draw(a) {
        decoratedShape.draw();
        // Add decoration function
        setRedBorder(decoratedShape);
    }
    // Private coloring method
    private void setRedBorder(Shape decoratedShape){
        System.out.println("Border Color: Red"); }}Copy the code

The client code is used like this

public class DecoratorPatternDemo {
    public static void main(String[] args){

        Shape circle = new Circle();

        // The Cirle that is decorated by the decoration class is red.
        Shape redCircle = new RedShapeDecorator(new Circle());

        / / common round
        circle.draw();
        // The red circleredCircle.draw(); }}Copy the code

conclusion

Decoration pattern is one of the structural patterns, mainly used to solve the problem of adding some useful small functions to the class and object without changing the structure of the original class and object.

This paper reference www.tutorialspoint.com/design_patt…

Recommended reading

1. Java concurrent programming stuff (10) — Final summary

2. Common network problem locating tools that programmers should master

3. Do you know how to use Awk

4. Teach you how to build a set of ELK log search operation and maintenance platform