当前位置:网站首页>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 01:28:00 【Java technology stack】
Click on the official account ,Java dried food Timely delivery 
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/javastack
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/javastack
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 .


Good start ! Reissue 10,000 Red envelope cover
2021 What happened in 10 It's a technical event !!
23 Design mode and Practice ( Very comprehensive )
replace Log4j2!tinylog Born in the sky
Goodbye, single dog !Java Create the object's 6 Ways of planting
Explode !Java Xie Cheng is coming !
Weigh on Guan Xuan :Redis Here comes the object mapping framework !!
Recommend a code artifact , Save at least half the amount of code !
Spring Boot 3.0 M1 Release , Formal abandonment Java 8
Spring Boot Learning notes , This is so complete !
Focus on Java Technology stack, see more dry goods


obtain Spring Boot Practical notes !
边栏推荐
- Advanced data storage
- Elegant throttling / de buffeting decorator under LAYA
- pca从0到1
- Simulated 100 questions and simulated examination for safety management personnel of metal and nonmetal mines (small open pit quarries) in 2022
- [path of system analysts] summary of real problems of system analysts over the years
- 实体类DTO转VO通过插件转化
- Simulated 100 questions and simulated examination for safety management personnel of metal and nonmetal mines (small open pit quarries) in 2022
- Markov networks and conditional random fields
- Weibull Distribution韦布尔分布的深入详述(1)原理和公式
- 2022年金属非金属矿山(小型露天采石场)安全管理人员考试模拟100题及模拟考试
猜你喜欢

A knowledge map (super dry goods, recommended collection!)
![[project training] wechat official account to obtain user openid](/img/54/0a77e4441ee87e6ff04f3f07baa965.png)
[project training] wechat official account to obtain user openid

Jvm: thread context classloader

PCA from 0 to 1

Program environment and pretreatment

Recursive and non recursive transformation

Defect detection, introduction to Halcon case.

Zhongchuang patents | China has 18000 necessary patents for 5g standards, respects intellectual property rights and jointly builds a strong intellectual property country

100 deep learning cases | day 41: speech recognition - pytorch implementation

MySQL实训报告【带源码】
随机推荐
[project training] JWT
Weekly CTF week 1: Amazing tapes
LabVIEW Arduino electronic weighing system (project Part-1)
Article 3: Design of multifunctional intelligent trunk following control system | undergraduate graduation project - [defense ppt]
Websocket server practice
jvm: 线程上下文类加载器(TheadContextClassLoader)
A knowledge map (super dry goods, recommended collection!)
Loop loop and CX
Operation of simulated examination platform of diazotization process examination question bank in 2022
Crawler small case 04 - use beautiful soup to batch obtain pictures
Article 5: Design of multi-functional intelligent trunk following control system | undergraduate graduation design - [learning of controller arduino+stm32]
I worked as a software testing engineer in a large factory and wrote "one day's complete workflow"
人们对于产业互联网的这样一种认识的转变,并不是一蹴而就的
Codemirror 2 - highlight only (no editor) - codemirror 2 - highlight only (no editor)
Blue Bridge Cup - 2012b Group real question 3 specific drinking capacity
Zhongchuang patents | China has 18000 necessary patents for 5g standards, respects intellectual property rights and jointly builds a strong intellectual property country
Practice of Flink CDC + Hudi massive data entering the lake in SF
一看就懂的JMeter操作流程
Forecast report on market demand and future prospect of cvtf industry of China's continuously variable transmission oil
I'm fired because I can only test basic functions····