MindMap Gallery Design Pattern
This is a mind map about design patterns, the main contents include: adapter mode, delegation mode, policy mode, template mode, prototype mode (creation mode), design mode classification, agent mode provides an agent for other objects to control access to this object, singleton mode, factory mode, and design principles.
Edited at 2025-02-23 19:08:11This template shows the structure and function of the reproductive system in the form of a mind map. It introduces the various components of the internal and external genitals, and sorts out the knowledge clearly to help you become familiar with the key points of knowledge.
This is a mind map about the interpretation and summary of the relationship field e-book, Main content: Overview of the essence interpretation and overview of the relationship field e-book. "Relationship field" refers to the complex interpersonal network in which an individual influences others through specific behaviors and attitudes.
This is a mind map about accounting books and accounting records. The main contents include: the focus of this chapter, reflecting the business results process of the enterprise, the loan and credit accounting method, and the original book of the person.
This template shows the structure and function of the reproductive system in the form of a mind map. It introduces the various components of the internal and external genitals, and sorts out the knowledge clearly to help you become familiar with the key points of knowledge.
This is a mind map about the interpretation and summary of the relationship field e-book, Main content: Overview of the essence interpretation and overview of the relationship field e-book. "Relationship field" refers to the complex interpersonal network in which an individual influences others through specific behaviors and attitudes.
This is a mind map about accounting books and accounting records. The main contents include: the focus of this chapter, reflecting the business results process of the enterprise, the loan and credit accounting method, and the original book of the person.
Design Pattern
Design Principles
SOLID
Single ResponsibilityPrinciple
A class should have only one reason for change, otherwise the class should be split
Opening and closing principle
Open to extensions, close to modifications
Lisch replacement principle
Subclasses can extend the functions of the parent class, but cannot change the original functions of the parent class.
Interface isolation principle
Interface splitting is smaller and more dedicated
Reliance inversion principle
When designing code structures, high-level modules should not rely on low Layer modules, both should rely on abstraction, abstraction should not rely on details, details should The dependency is abstract.
KISS Principles
Keep it simple and stupid
YAGNI Principles
Don't over-design
DRY Principle
Don't write duplicate code
Dimit's Law
The core theme is that an object should keep the least understanding of other objects. In order to reduce the coupling between classes, the more independent each class is, the better.
Design Pattern Classification
Creation type: 5 kinds of object creation process
Factory method mode
Abstract factory pattern
Singleton mode
Builder Mode
Prototype mode
Structural type: Processing classes or combinations of objects, 7 types
Adapter mode
Decorator mode
Agent Mode
Appearance mode
Bridge mode
Combination mode
Enjoy the Yuan mode
Behavior type: describes how classes or objects interact and how to assign responsibilities, 11 types
Policy Mode
Template method pattern
Observer mode
Iterator mode
Responsibility chain model
Command Mode
Memo mode
Status Mode
Visitor Mode
Intermediary model
Interpreter mode
Factory model
Simple factory mode
Factory method mode
Abstract factory pattern
Singleton mode
Hungry style: Create object initialization when loading
Lazy style: create an object instance when calling
Static inner class: create object instances in the inner class
Enumerated singletons: thread-safe, only loaded once, enumerated classes are all singleton classes. The only singleton pattern that will not be destroyed now (solves reflection and serialization breakdown bad)
Reflection destroys singleton: Although the constructor is set to private, it can be accessed by setting force To call its constructor, solution: throw an exception in the private constructor and prohibit reflection creation.
Serialization destroys singleton: The deserialized object will re-allocate memory, that is, re-create. Solution: Add readResolve method
Container-style single case
Proxy mode provides a proxy for other objects to control access to this object.
Static proxy analysis:
Add some extra functionality without modifying the original service class
shortcoming: 1. The number of classes needs to be increased 2. Not flexible enough 3. High maintenance cost
Dynamic proxy analysis
Implementation method
Dynamic proxy based on JDK
The general process is:
1. Create a JDK dynamic proxy object and pass the MemberServiceImpl object as a target parameter.
2. Then call the getProxy method, which calls Proxy.newProxyInstance to load the proxy object of this MemberServiceImpl.
3. Call the login method through the generated proxy object, which is not the method of MemberServiceImpl itself, but is called into the invoke method in the InvocationHandler.
4. Corresponding enhancements can be made in the invoke method, where the method parameter is the method of the proxy object, and args is the method of the proxy object
Source code JDK dynamic proxy analysis
newProxyInstance Analysis
(Preliminary verification) Before creating an agent, some basic verification will be done first, such as empty parameter verification and security inspection.
1. Proxy object generation) Here getProxyClass0 is a very important piece of logic, which will generate the bytecode of the proxy object and load the proxy object into JVM memory.
2. Enter the getProxyClass0 method to analyze. This logic first also did a check. Then try to get the proxy class from the proxy class cache. If it exists, it will return directly. This step is to improve the efficiency of obtaining the proxy class. Don't generate it every time. If it does not exist, a proxy class is generated and added to the cache.
3. Then go to the proxyClassCache.get(loader, interfaces) method to analyze it. This step mainly involves doing some basic verification, and then you need to get the corresponding value from the cache map, that is, the valuesMap parameter. If it does not exist, we need to initialize it and initialize it into an empty ConcurrentHashMap.
3. Then the code goes down. This step is to get the corresponding Supplier from the second level of the map ConcurrentMap<Object, Supplier<V>>. If Supplier does not exist, you need to create a Factory assign to Supplier. If it exists, you will get it directly. Then, you need to use the supplier's get() method to create the bytecode corresponding to the proxy class and load the bytecode into JVM memory. This method is the core logic here.
4. Then let’s take a look at how the get() method in this supplier is called. Here you jump to the get() method in Factory. The logic of this code is mainly to create value, that is, to create proxy objects, but thread safety is also needed here. For example, if the supplier in the cache is modified, it cannot be executed further.
5. Then look at the place where the proxy object is actually created valueFactory.apply(key, parameter), which is done through valueFactory. This valueFactory is ProxyClassFactory, a proxy class factory. As the name suggests, this factory is used to produce proxy classes. First of all, this logic is non-core logic, which roughly verifies the validity of the interface array and ensures that the interface implemented in the generated proxy class is valid.
6. The next logic is to determine the package name and class name of the proxy class to be generated. The logic is: if there are non-public interfaces in the incoming interface, the generated proxy class will be in the package where these non-public interfaces reside. If all interfaces are public interfaces, the proxy class will be in the default package com.sun.proxy. The default proxy class is not generated into the file system. You can configure the parameter -Dsun.misc.ProxyGenerator.saveGeneratedFiles=true in the VM parameters when the project starts. Then the bytecode of the proxy class can be generated into the file system.
7. The next step is the most core logic, generating bytecode and loading it into memory, so that the proxy class can be used through the Class object in the future. This is the process of generating proxy classes through JDK dynamic proxy. After the execution here is completed, Class<?> cl = getProxyClass0(loader, intfs); This logic can return the created proxy class.
8. The next step is the last step, which will create the proxy class into a proxy object. This proxy object implements the specified interface and delegates the method call to the specified InvocationHandler.
Dynamic proxy based on CGLIB.
The general process
1. There is a normal class called LoginService, which contains a login method for performing login operations. When this method is called, it outputs a line of text on the console.
2. There is a class called CglibDynamicProxy that implements the MethodInterceptor interface. The purpose of this class is to create a CGLIB dynamic proxy object to execute methods instead of other objects.
3. In the constructor of the CglibDynamicProxy class, it receives a target object, indicating the object you want to proxy.
4. The getProxy method is used to create a proxy object. It uses CGLIB's Enhancer class, takes the target object's class as the superclass (parent class), and sets the current object as a method interceptor (this represents the current object). It then creates the proxy object using Enhancer and returns.
5. In the intercept method, when the method of the proxy object is called, it will first output a line of text to indicate the beginning of the CGLIB dynamic proxy, and then call the corresponding method of the target object. Then, it outputs a line of text again to indicate the end of the CGLIB dynamic proxy.
6. In the CglibDynamicTest class, we create a CglibDynamicProxy object and pass the LoginService object to it as the target. We then use the getProxy method to get the proxy object and transform it into the LoginService type.
7. Finally, we use the proxy object to call the login method. Each time a method is called, the proxy will output text before and after the method to indicate the beginning and end of the CGLIB dynamic proxy.
The difference between two dynamic proxy
1. Different implementation methods
JDK dynamic proxy implements all interfaces of the proxy object through reflection, so JDK can only proxy objects that implement interface objects;
CGLlib will rewrite all methods of the proxy class, so not all methods can be proxied (private and final cannot be used);
2. Different ways to intercept proxy objects
JDK dynamic proxy is implemented by implementing the InvocationHandler interface. When the proxy object calls any method, it will first enter the InvocationHandler's invoke() method, and this method determines whether to call the original object's method;
CGLIB dynamic proxy uses subclasses of the target class, overwrites the business methods, and adds cross-cutting logic to achieve interception;
3. Different performance and efficiency
JDK dynamic proxy and CGLib proxy both generate new bytecode during the runtime, but CGLib implementation is more complex and uses the ASM framework. The efficiency of generating proxy classes is lower than that of JDK;
JDK dynamic proxy querys the interfaces of all proxy objects through reflection mechanisms, and CGLib proxy calls methods directly through FastClass mechanism, so the execution efficiency is that CGLib is higher than JDK proxy;
Pros and cons
advantage
It can separate the proxy object from the real called target object, reduce the degree of coupling of the system, and is easy to expand. While enhancing the responsibilities of the target object, it can play a role in protecting the object.
shortcoming
Increasing the complexity of the system will add a proxy object between the client and the target object, and the request speed will slow down.
shortcoming
The state proxy is implemented based on reflection. When running, it needs to execute the reflection logic. The performance still has certain losses, but the impact is not large.
Prototype mode (creation mode)
Core idea: Based on an existing one Copy an object out of the object, and reduce the direct creation of the object through copying. cost.
Deep copy
Two ways to implement
One is to copy the object recursively
The second type is to do it through object serialization.
Shallow copy: Only copy addresses: Both objects depend on the same object
Summarize:
The shallow copy will only copy the basic data type inside the object and the memory address of the reference object, and will not copy recursively. Reference objects, and reference objects that reference objects
And deep copy means completely copying a new object. Therefore, deep copy operations will be more effective than shallow copy The performance is even worse. At the same time, the shallow copy code is a little simpler to write than the deep copy code.
If the object we copied is immutable, that is, my object will only Check it, it will not add, delete and modify it, then just use a shallow copy. If you copy it If there are additions, deletions and modifications of objects, then deep copy is required.
In short, it must be appropriately detailed and depends on the actual situation of the project.
Template pattern
The framework for defining business processing processes in the parent class and performing specific implementations in the subclass
Policy Mode
Define a main interface, and then many classes implement this interface
Delegation mode
It's a oriented The basic function of the design pattern of the image is to be responsible for the call and allocation of tasks; It is a special static proxy, which can be understood as a full-right proxy (Agent mode note Focus on process, while delegation mode focuses on results), delegation mode belongs to behavioral models style does not belong to the GOF23 design modes;
Adapter mode
The core idea is to interface a class Convert it into another interface that customers want. To put it bluntly, it can be done through the adapter. Combine interfaces or classes that are otherwise mismatched and incompatible