JDK Those design patterns are used ?Spring Those design patterns are used ? These two questions , It’s common in interviews . I searched the Internet about Spring The explanation of design patterns in is almost the same , And most of them are very old . therefore , It took a few days to sum up , Because of my limited personal ability , If there is any mistake in the article, you can point out . in addition , Limited article space , For the design pattern and some source code interpretation, I just mentioned , The main purpose of this article is to review Spring Design patterns in .
Design Patterns( Design patterns ) Represents the best computer programming practice in object-oriented software development . Spring Different types of design patterns are widely used in the framework , Let’s take a look at the design patterns ?
Inversion of control (IoC) And dependency injection (DI)
IoC(Inversion of Control, Inversion of control ) yes Spring One of the most important concepts , It’s not a technology , It’s a decoupled design idea . Its main purpose is to rely on “ The third party ”(Spring Medium IOC Containers ) Decouple objects with dependency (IOC Container management object , You just use it ), So as to reduce the coupling between codes .IOC It’s a principle , Not a pattern , The following patterns ( But not limited to, ) Realized IoC principle .
Spring IOC The container is like a factory , When we need to create an object , Just configure the configuration file / Annotations can be , It doesn’t matter how objects are created . IOC The container is responsible for creating objects , Connect objects together , Configure these objects , And process the entire life cycle of these objects from creation , Until they are completely destroyed .
In a real project Service If a class has hundreds or even thousands of classes as its underlying layer , We need to instantiate this Service, You may have to figure this out every time Service Constructors of all underlying classes , It can drive people crazy . If the use of IOC Words , You just need to configure , Then quote where you need it , This greatly increases the maintainability of the project and reduces the development difficulty . About Spring IOC The understanding of the , Recommend to see this answer of Zhihu :https://www.zhihu.com/question/23277575/answer/169698662 , Very good .
How to understand inversion of control ? for instance :” object a Depends on the object b, Be the object a Need to use object b You have to create it yourself . But when the system introduces IOC After container , object a And the object b Lost direct contact before . This is the time , Be the object a Need to use object b When , We can specify IOC Container to create an object b Inject to object a in “. object a Get dependent objects b The process of , From active behavior to passive behavior , Reversal of control , This is the name of inversion of control .
DI(Dependecy Inject, Dependency injection ) It is a design pattern to realize the inversion of control , Dependency injection is to pass instance variables into an object .
Factory design mode
Spring Using factory mode, you can BeanFactory
or ApplicationContext
establish bean object .
Both comparisons :
BeanFactory
: Injection delay ( Apply to a bean Only when it’s time to inject ), Compared withApplicationContext
It takes up less memory , The program starts faster .ApplicationContext
: When the container starts , Whether you use it or not , Create all at once bean .BeanFactory
Only the most basic dependency injection support is provided ,ApplicationContext
ExpandedBeanFactory
, Except forBeanFactory
There’s more to it , So the average developer usesApplicationContext
There will be more .
ApplicationContext Three implementation classes of :
ClassPathXmlApplication
: Treat the context file as a classpath resource .FileSystemXmlApplication
: From the file system XML File load context definition information .XmlWebApplicationContext
: from Web In the system XML File load context definition information .
Example:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class App {
public static void main(String[] args) {
ApplicationContext context = new FileSystemXmlApplicationContext(
"C:/work/IOC Containers/springframework.applicationcontext/src/main/resources/bean-factory-config.xml");
HelloApplicationContext obj = (HelloApplicationContext) context.getBean("helloApplicationContext");
obj.getMsg();
}
}
Singleton design pattern
In our system , There are some objects that we just need , for instance : Thread pool 、 cache 、 Dialog box 、 The registry 、 Log object 、 Act as a printer 、 Graphics card and other device drivers . in fact , This type of object can only have one instance , If you make multiple instances, it may lead to some problems , such as : The behavior of the program is abnormal 、 Overuse of resources 、 Or inconsistent results .
The advantages of using singleton mode :
- For frequently used objects , You can omit the time it takes to create an object , For those heavyweight objects , It’s a very significant overhead ;
- because new Reduce the number of operations , Therefore, the frequency of using system memory will be reduced , This will lessen GC pressure , To shorten the GC Pause time .
Spring in bean The default scope of is singleton( Single case ) Of . except singleton Scope ,Spring in bean There are also several scopes :
- prototype : Each request creates a new bean example .
- request : every time HTTP Requests all produce a new bean, The bean At present only HTTP request Effective within .
- session : every time HTTP Requests all produce a new bean, The bean At present only HTTP session Effective within .
- global-session: overall situation session Scope , Just based on portlet Of web It’s the application that makes sense ,Spring5 No more .Portlet It can generate semantic code ( for example :HTML) The small size of the clip Java Web plug-in unit . They are based on portlet Containers , Can be like servlet Handle it the same way HTTP request . however , And servlet Different , Every portlet There are different conversations
Spring The way to implement the singleton :
- xml :
<bean id="userService" class="top.snailclimb.UserService" scope="singleton"/>
- annotation :
@Scope(value = "singleton")
Spring adopt ConcurrentHashMap
The special way to realize singleton registry is to realize singleton mode .Spring The core code to implement the singleton is as follows
// adopt ConcurrentHashMap( Thread safety ) Implement single instance registry
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(64);
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "'beanName' must not be null");
synchronized (this.singletonObjects) {
// Check for instances in the cache
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
//... A lot of code is omitted
try {
singletonObject = singletonFactory.getObject();
}
//... A lot of code is omitted
// If the instance object does not exist , We register in the single instance registry .
addSingleton(beanName, singletonObject);
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
}
// Add objects to the singleton registry
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
this.singletonObjects.put(beanName, (singletonObject != null ? singletonObject : NULL_OBJECT));
}
}
}
Agent design pattern
The agent mode is AOP Application in
AOP(Aspect-Oriented Programming: Section oriented programming ) Be able to make those irrelevant to the business , The logic or responsibility jointly called by business modules ( For example, transaction processing 、 Log management 、 Authority control, etc ) encapsulated , Easy Reduce the repetitive code of the system , Reduce the coupling between modules , and It’s good for future expansibility and maintainability .
Spring AOP It’s based on dynamic agents , If the object to be represented , Implemented an interface , that Spring AOP Will use JDK Proxy, To create a proxy object , For objects that do not implement interfaces , Can’t use JDK Proxy Went to the agency , Now Spring AOP Will use Cglib , Now Spring AOP Will use Cglib Generate a subclass of the surrogate object to act as a proxy , As shown in the figure below :
You can also use it AspectJ ,Spring AOP It’s integrated AspectJ ,AspectJ It should be counted as Java The most complete ecosystem AOP The framework .
Use AOP Then we can abstract some general functions , Use it directly where you need it , This greatly simplifies the amount of code . It’s also convenient when we need to add new features , This also improves system scalability . Log function 、 Transaction management and other scenarios are used AOP .
Spring AOP and AspectJ AOP What’s the difference? ?
Spring AOP Belongs to runtime enhancements , and AspectJ It’s compile time enhancements . Spring AOP Based on Agent (Proxying), and AspectJ Operation based on bytecode (Bytecode Manipulation).
Spring AOP It’s integrated AspectJ ,AspectJ It should be counted as Java The most complete ecosystem AOP The framework .AspectJ Compared with Spring AOP More powerful , however Spring AOP It’s relatively simpler ,
If we have fewer sections , So the performance difference between the two is not big . however , When there are too many aspects , Best choice AspectJ , It is better than Spring AOP Much faster .
Template method
Template method pattern is a behavior design pattern , It defines the skeleton of the algorithm in an operation , Instead, defer some steps to subclasses . Template method allows subclasses to redefine the implementation of some specific steps of an algorithm without changing the structure of the algorithm .
public abstract class Template {
// This is our template method
public final void TemplateMethod(){
PrimitiveOperation1();
PrimitiveOperation2();
PrimitiveOperation3();
}
protected void PrimitiveOperation1(){
// The current class implementation
}
// Quilt class implementation method
protected abstract void PrimitiveOperation2();
protected abstract void PrimitiveOperation3();
}
public class TemplateImpl extends Template {
@Override
public void PrimitiveOperation2() {
// The current class implementation
}
@Override
public void PrimitiveOperation3() {
// The current class implementation
}
}
Spring in jdbcTemplate
、hibernateTemplate
Such as to Template The end of the database operation class , They use the template pattern . In general , We all use inheritance to implement template pattern , however Spring Not in this way , But use Callback Pattern matches template method pattern , It achieves the effect of code reuse , At the same time, it increases the flexibility .
Observer mode
The observer pattern is an object behavior pattern . It represents a dependency relationship between objects , When an object changes , The objects on which this object depends will also react .Spring Event driven model is a classic application of observer pattern .Spring The event driven model is very useful , In many scenarios, we can decouple our code . For example, we need to update the product index every time we add products , At this point, the observer model can be used to solve this problem .
Spring Three roles in the event driven model
The role of the event
ApplicationEvent
(org.springframework.context
It’s a bag ) Play the role of an event , This is an abstract class , It inherited java.util.EventObject
And implemented java.io.Serializable
Interface .
Spring The following events exist by default in , They are all right ApplicationContextEvent
The implementation of the ( Inherited from ApplicationContextEvent
):
ContextStartedEvent
:ApplicationContext
Events triggered after startup ;ContextStoppedEvent
:ApplicationContext
Events triggered after stop ;ContextRefreshedEvent
:ApplicationContext
Events triggered after initialization or refresh complete ;ContextClosedEvent
:ApplicationContext
Events triggered after shutdown .
The role of event monitor
ApplicationListener
Acting as an event monitor , It’s an interface , There is only one definition in it onApplicationEvent()
Method to handle ApplicationEvent
.ApplicationListener
The interface class source code is as follows , You can see the definition of the interface and see the events in the interface as long as they are implemented ApplicationEvent
That’s all right. . therefore , stay Spring We only need to achieve ApplicationListener
Interface onApplicationEvent()
Method to complete the listening event
package org.springframework.context;
import java.util.EventListener;
@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
void onApplicationEvent(E var1);
}
The role of the event publisher
ApplicationEventPublisher
Acting as the publisher of the event , It’s also an interface .
@FunctionalInterface
public interface ApplicationEventPublisher {
default void publishEvent(ApplicationEvent event) {
this.publishEvent((Object)event);
}
void publishEvent(Object var1);
}
ApplicationEventPublisher
Interface publishEvent()
This method is AbstractApplicationContext
Class is implemented , Read the implementation of this method , You’ll actually find out through events ApplicationEventMulticaster
Came to broadcast . Too much detail , It’s not here to analyze , A separate article may be written later to mention .
Spring Summary of the event process
- Define an event : Implement an inheritance from
ApplicationEvent
, And write the corresponding constructor ; - Define an event listener : Realization
ApplicationListener
Interface , rewriteonApplicationEvent()
Method ; - Use event publishers to post messages : Can pass
ApplicationEventPublisher
OfpublishEvent()
Method to publish a message .
Example:
// Define an event , Inherited from ApplicationEvent And write the corresponding constructor
public class DemoEvent extends ApplicationEvent{
private static final long serialVersionUID = 1L;
private String message;
public DemoEvent(Object source,String message){
super(source);
this.message = message;
}
public String getMessage() {
return message;
}
// Define an event listener , Realization ApplicationListener Interface , rewrite onApplicationEvent() Method ;
@Component
public class DemoListener implements ApplicationListener<DemoEvent>{
// Use onApplicationEvent receive messages
@Override
public void onApplicationEvent(DemoEvent event) {
String msg = event.getMessage();
System.out.println(" The message received is :"+msg);
}
}
// Release events , Can pass ApplicationEventPublisher Of publishEvent() Method to publish a message .
@Component
public class DemoPublisher {
@Autowired
ApplicationContext applicationContext;
public void publish(String message){
// Release events
applicationContext.publishEvent(new DemoEvent(this, message));
}
}
When calling DemoPublisher
Of publish()
Method time , such as demoPublisher.publish(" Hello ")
, The console will print out : The message received is : Hello
.
Adapter pattern
Adapter pattern (Adapter Pattern) Convert one interface to another that the customer wants , The adapter pattern enables classes that are not compatible with the interface to work together , It is alias wrapper (Wrapper).
spring AOP Adapter mode in
We know Spring AOP The implementation of is based on the agent mode , however Spring AOP An enhancement or notification of (Advice) Using adapter mode , The interface associated with it is AdvisorAdapter
.Advice Common types are :BeforeAdvice
( Before the target method is called , Pre notice )、AfterAdvice
( After the target method is called , The rear notice )、AfterReturningAdvice
( After the execution of the target method ,return Before ) wait . Each type Advice( notice ) There are corresponding interceptors :MethodBeforeAdviceInterceptor
、AfterReturningAdviceAdapter
、AfterReturningAdviceInterceptor
.Spring The predefined notification is passed through the corresponding adapter , Adaptation MethodInterceptor
Interface ( method interceptors ) Object of type ( Such as :MethodBeforeAdviceInterceptor
Be responsible for adaptation MethodBeforeAdvice
).
spring MVC Adapter mode in
stay Spring MVC in ,DispatcherServlet
Call according to the request information HandlerMapping
, Parse the request corresponding to Handler
. Resolve to the corresponding Handler
( That’s what we usually say Controller
controller ) after , Start with HandlerAdapter
Adapter handling .HandlerAdapter
As the expected interface , The specific adapter implementation class is used to adapt the target class ,Controller
As a class that needs to be adapted .
Why are you in Spring MVC Using adapter mode ? Spring MVC Medium Controller
There are many kinds , Different types of Controller
Processing requests in different ways . If you don’t use adapter mode ,DispatcherServlet
Get the corresponding type of Controller
, Judge for yourself what you need , Like the following code :
if(mappedHandler.getHandler() instanceof MultiActionController){
((MultiActionController)mappedHandler.getHandler()).xxx
}else if(mappedHandler.getHandler() instanceof XXX){
...
}else if(...){
...
}
If we add another Controller
The type needs to add another line to the code above Judgment statement , This form makes the program difficult to maintain , It also violates the open close principle of design patterns – Open to expansion , Turn off for changes .
Decorator mode
Decorator pattern can dynamically add additional properties or behaviors to an object . Compared to using inheritance , Decorator mode is more flexible . In short, when we need to modify the original function , But we don’t want to modify the original code directly , To design a Decorator Outside the original code . Actually in JDK The decorator pattern is used in many places , such as InputStream
family ,InputStream
Under class FileInputStream
( Read the file )、BufferedInputStream
( Add cache , Greatly improve the speed of reading files ) All subclasses are not modified InputStream
In the case of code, it extends its function .
Spring Middle configuration DataSource When ,DataSource It could be different databases and data sources . Can we dynamically switch between different data sources with less modification of the original class code according to the needs of customers ? At this time we need to use decorator mode ( I don’t quite understand the principle of this ).Spring The wrapper pattern used in contains… In the class name Wrapper
perhaps Decorator
. These classes basically add extra responsibilities to an object dynamically
summary
Spring What design patterns are used in the framework ?
- Factory design mode : Spring Use factory mode through
BeanFactory
、ApplicationContext
establish bean object . - Agent design pattern : Spring AOP Function realization .
- Singleton design pattern : Spring Medium Bean By default, it’s single .
- Template method pattern : Spring in
jdbcTemplate
、hibernateTemplate
Such as to Template The end of the database operation class , They use the template pattern . - Packaging design pattern : Our project needs to connect to multiple databases , Moreover, different customers will access different databases according to their needs in each visit . This mode allows us to dynamically switch different data sources according to the needs of customers .
- Observer mode : Spring Event driven model is a classic application of observer pattern .
- Adapter pattern :Spring AOP An enhancement or notification of (Advice) Using adapter mode 、spring MVC Adapter pattern adaptation is also used in
Controller
. - ……
Reference resources
- 《Spring Technology insider 》
- https://blog.eduonix.com/java-programming-2/learn-design-patterns-used-spring-framework/
- http://blog.yeamin.top/2018/03/27/ The singleton pattern -Spring Principle analysis of single example implementation /
- https://www.tutorialsteacher.com/ioc/inversion-of-control
- https://design-patterns.readthedocs.io/zh_CN/latest/behavioral_patterns/observer.html
- https://juejin.im/post/5a8eb261f265da4e9e307230
- https://juejin.im/post/5ba28986f265da0abc2b6084
author :Snailclimb
link :Spring Those design patterns are used in ?
source :github