当前位置:网站首页>Don't write about the full screen explosion, try the decorator mode, this is the elegant way!!

Don't write about the full screen explosion, try the decorator mode, this is the elegant way!!

2022-06-12 23:23:00 Java technology stack

background

Are you still writing about explosions on the screen ?

No matter three, seven, twenty-one , Write all the code in one class , This code is not elegant, do not say , If the change involves old code , It may also affect the stability of the online system .

Actually , Many situations , We can solve many potential system problems by skillfully using design patterns , Today, the stack leader will teach you to use the decorator mode , Extend the function without changing the old code , It can not only improve the elegance of the code , Without affecting existing functions , Who knows , It's delicious !!

What is the decorator mode ?

Decorator mode , Literally , seeing the name of a thing one thinks of its function , It's a decorative pattern , It can be used without changing the original code , For existing objects 、 Conduct a new level of packaging 、 decorate , Enhance the original basic functions to provide richer capabilities .

Take a small example of simple decoration :

clear > Puttying > Paint > Hang murals

It can also be :

clear > Puttying > Paste marble > Hang up TV

Or it could be :

clear > Puttying > Wallpaper

This is a simple step-by-step process of decorating the wall ( ha-ha , About that , I'm not a professional ), This is the decorator mode , Each step of decoration does not interfere with each other , But the later steps need to rely on the completion of the previous step , The following steps can be continuously added on the basis of the previous decoration .

The structure diagram of decorator mode is as follows :

The structure of decorator pattern class is as follows :

  • Component: Component interface class , Define the basic functions of the decorated class
  • ConcreteComponent: Basic implementation class of component interface
  • Decorator: Decorator role class , Implement and hold one Component Object instances
  • ConcreteDecorator: Implementation class of decorator

Advantages of decorator mode :

1、 Do not change the original code , Dynamic add function ;

2、 Objects are not interdependent , loose coupling , Elegant enough ;

3、 Comply with opening and closing principle , Good scalability 、 Easy to maintain ;

Disadvantages of decorator mode :

1、 If there are many decoration links , It will cause the expansion of decorators ;

2、 The nesting of decorators is complex , Users must be aware of all types of ornaments and their uses ;

Decorator mode actual combat

Let's implement the above decoration case with decorator mode .

Component interface class :

/**
 *  Wall decoration interface 
 * @author:  Stack leader 
 * @from:  official account Java Technology stack 
 */
public interface WallBeautify {

    /**
     *  Decoration operation 
     * @author:  Stack leader 
     * @from:  official account Java Technology stack 
     */
    void operation();

}

Basic implementation class of component interface :

/**
 *  Wall decoration is basically realized ( Clean the wall )
 * @author:  Stack leader 
 * @from:  official account Java Technology stack 
 */
public class WallBeautifyClean implements WallBeautify {

    @Override
    public void operation() {
        System.out.println(" Start cleaning the wall ");
    }

}

Decorator role class :

This is an abstract class , Implement and hold one Component Object instances , Aggregation is used here , Not inheritance , This is also the key point of decorator mode .

/**
 *  Role of wall decoration decorator 
 * @author:  Stack leader 
 * @from:  official account Java Technology stack 
 */
public abstract class WallBeautifyDecorator implements WallBeautify {

    /**
     *  Hold one  Component  Object instances 
     * @author:  Stack leader 
     * @from:  official account Java Technology stack 
     */
    private WallBeautify wallBeautify;

    public WallBeautifyDecorator(WallBeautify wallBeautify) {
        this.wallBeautify = wallBeautify;
    }

    @Override
    public void operation() {
        wallBeautify.operation();
        decoration();
    }

    /**
     *  Decorator implementation class custom implementation method 
     * @author:  Stack leader 
     * @from:  official account Java Technology stack 
     */
    public abstract void decoration();

}

Overwrite the original operation method , Decorate after the original operation , So we need to provide an abstract decoration Method for different decorator implementation classes to implement .

Implementation class of decorator :

It's defined here 3 A decoration process :

Puttying > Paint > Hang murals

So they inherit Decorator role class And realize its decoration method :

/**
 *  Role realization of wall decoration decorator ( Puttying )
 * @author:  Stack leader 
 * @from:  official account Java Technology stack 
 */
public class WallBeautifyPutty extends WallBeautifyDecorator {

    public WallBeautifyPutty(WallBeautify wallBeautify) {
        super(wallBeautify);
    }

    @Override
    public void decoration() {
        System.out.println(" Start puttying ");
    }

}
/**
 *  Role realization of wall decoration decorator ( Paint )
 * @author:  Stack leader 
 * @from:  official account Java Technology stack 
 */
public class WallBeautifyPaint extends WallBeautifyDecorator {

    public WallBeautifyPaint(WallBeautify wallBeautify) {
        super(wallBeautify);
    }

    @Override
    public void decoration() {
        System.out.println(" Start painting ");
    }

}
/**
 *  Role realization of wall decoration decorator ( Hang murals )
 * @author:  Stack leader 
 * @from:  official account Java Technology stack 
 */
public class WallBeautifyHang extends WallBeautifyDecorator {

    public WallBeautifyHang(WallBeautify wallBeautify) {
        super(wallBeautify);
    }

    @Override
    public void decoration() {
        System.out.println(" Start hanging murals ");
    }

}

Test it :

/**
 *  Decorator pattern test class 
 * @author:  Stack leader 
 * @from:  official account Java Technology stack 
 */
public class DecoratorTest {

    public static void main(String[] args) {
        //  Clean the wall 
        WallBeautify wallBeautifyClean = new WallBeautifyClean();
        wallBeautifyClean.operation();
        System.out.println("--------------");

        //  Puttying 
        WallBeautify wallBeautifyPutty = new WallBeautifyPutty(wallBeautifyClean);
        wallBeautifyPutty.operation();
        System.out.println("--------------");

        //  Paint 
        WallBeautify wallBeautifyPaint = new WallBeautifyPaint(wallBeautifyPutty);
        wallBeautifyPaint.operation();
        System.out.println("--------------");

        //  Hang murals 
        WallBeautify wallBeautifyHang = new WallBeautifyHang(wallBeautifyPaint);
        wallBeautifyHang.operation();
        System.out.println("--------------");

        //  Multilayer nesting 
        WallBeautify wbh = new WallBeautifyHang(new WallBeautifyPaint(
                new WallBeautifyPutty(new WallBeautifyClean())));
        wbh.operation();
        System.out.println("--------------");
    }

}

All the actual source code of this tutorial has been uploaded to this warehouse :

https://github.com/javastacks...

Output results :

 Start cleaning the wall 
--------------
 Start cleaning the wall 
 Start puttying 
--------------
 Start cleaning the wall 
 Start puttying 
 Start painting 
--------------
 Start cleaning the wall 
 Start puttying 
 Start painting 
 Start hanging murals 
--------------
 Start cleaning the wall 
 Start puttying 
 Start painting 
 Start hanging murals 
--------------

The result output is normal !

You can see , The use of decorator mode is relatively simple , Different decorative effects can be achieved by using decorator mode , In this way, the needs of different customers are met , Without changing the original code , It's still very fragrant .

follow-up 《 Design patterns 》 Serial articles in official account Java The technology stack is being updated , Please keep your attention !

The decorator mode is JDK Application in

Now we know how to use decorator mode , Now let's look at JDK Where is the decorator pattern used .

1、IO flow

The most classic application of decorator mode is JDK Medium IO It's gone (InputStream/ OutputStream)

frequently-used InputStream Class structure classes are as follows :

InputStream and FileInputStream Is the basic component interface and implementation .

FilterInputStream Is a decorator role that implements component interfaces and holds instance references :

BufferedInputStream、DataInputStream It's all different FilterInputStream Decorative realization of .

OutputStream It's the same principle .

2、 Synchronization set

Collection to be thread safe ( Such as :List、Set) Simply provide thread safe functions , Using decorator mode can also be easily realized .

Let's look at the methods of the synchronization collection tool class :

java.util.Collections#synchronizedList(List)

java.util.Collections#synchronizedSet(Set)

They are all SynchronizedCollection Decorator implementation class :

SynchronizedCollection It's a decorator role :

SynchronizedCollection Implements the collection component interface and holds the collection instance reference , and Collection(List) and ArrayList Is the basic component interface and implementation .

summary

This paper introduces the basic concept of decorator mode , Also made a basic actual combat , And gave two examples JDK Examples of decorator patterns in , I believe you have a basic understanding of the decorator mode , How to apply it to the project , Everyone should have a spectrum ?

Of course , The design pattern is just a reference for you , It should not be used blindly , Otherwise, it would be counterproductive . Words , How did you apply the decorator pattern in your project ? Welcome to leave a message and share the case !

All the actual source code of this tutorial has been uploaded to this warehouse :

https://github.com/javastacks...

Okay , Today's sharing is here , Later, I will update the actual articles of other design patterns , official account Java The first time the technology stack pushes .Java Technology stack 《 Design patterns 》 The series of articles are being updated , Please keep your attention !

Last , I think my article is very useful to you , Move your little hand , I'm looking at it 、 forward , Originality is not easy. , The stack leader needs your encouragement .

Copyright notice : The official account is No. "Java Technology stack " original , Reprint 、 Please indicate the source of this article , Plagiarism 、 If you wash your manuscript, you will complain about infringement , Consequence conceit , And reserves the right to pursue its legal liability .

Recent hot article recommends :

1.1,000+ Avenue Java Arrangement of interview questions and answers (2022 The latest version )

2. Explode !Java Xie Cheng is coming ...

3.Spring Boot 2.x course , It's too complete !

4.20w Programmer red envelope cover , Get it quickly ...

5.《Java Development Manual ( Song Mountain version )》 The latest release , Download it quickly !

I think it's good , Don't forget to like it + Forward !

原网站

版权声明
本文为[Java technology stack]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280955508842.html