Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the design patterns used in the Java Spring framework

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail what the design patterns used in the Java Spring framework are. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

1 simple factory model

When An object needs to call the method of B object, we need to new an instance of B in A, which we call hard-coding coupling, but the disadvantage is that once the requirement changes, for example, when we need to use class C instead of B, we have to rewrite the method of class A.

If thousands of classes in the application are hard-coded to couple B, it would be a headache to change.

So there is a simple factory pattern, also known as a static factory method, in which a factory class dynamically determines which product class should be created based on the parameters passed in.

BeanFactory in Spring is the embodiment of the simple factory pattern. BeanFactory is a core interface in the Spring IOC container, which is defined as follows:

You can get the Bean through its concrete implementation class (such as ClassPathXmlApplicationContext):

BeanFactory bf = new ClassPathXmlApplicationContext ("spring.xml"); User userBean = (User) bf.getBean ("userBean")

Instead of having to new themselves, the consumer gets the object instance through the getBean method of the factory class, which is the simple factory pattern, but Spring uses reflection to create the Bean.

2 factory method model

In a simple factory, all logical judgments and instance creation are made by the factory class.

If you do not want to judge in the factory class, you can provide different factories for different products, different factories produce different products, and each factory corresponds to only one corresponding object, which is the factory method pattern.

Spring FactoryBean, factory Bean

Define a class UserFactoryBean that implements the FactoryBean interface, mainly new a User object in the getObject method.

What is obtained through getBean (id) is the User instance generated by the factory, not the UserFactoryBean itself instance:

BeanFactory bf = new ClassPathXmlApplicationContext ("user.xml"); User userBean = (User) bf.getBean ("userFactoryBean"); 3 singleton mode

Only one instance of a class is allowed to be generated during the entire system operation.

Spring Bean defaults to singleton mode. Spring through the singleton registry (HashMap) way:

Public class DefaultSingletonBeanRegistry {/ / use ConcurrentHashMap to save various single instance objects private final Map singletonObjects = new ConcurrentHashMap; protected Object getSingleton (String beanName) {/ / go to Map first to get Object Object singletonObject = singletonObjects.get (beanName) / / if you don't get to create an object instance through reflection and add it to HashMap if (singletonObject = = null) {singletonObjects.put (beanName, Class.forName (beanName). NewInstance ());} / return object instance return singletonObjects.get (beanName);}} 4 proxy mode

It implements the same interface as the proxied object, and the client must interact with the proxied target class through the proxy, while the proxy generally carries out some specific processing in the process of interaction (before and after the interaction). For example, do pre-processing before calling this method and post-processing after calling this method.

Benefits

We can add some common logic to the business function of the target object, for example, if we want to add functions such as logging, rights management and transaction control to the target object, we can use the proxy class to do this, and there is no need to modify the target class. so that the target class remains stable.

In line with the principle of opening and closing, do not modify the code or methods written by others at will.

Agency is divided into

Static agent

You need to define an interface, and the proxied object (target object) and the proxy object (Proxy) implement the same interface together:

/ / Abstract interface public interface IStudentDao {void save ();} / Target object public class StudentDao implements IStudentDao {public void save () {System.out.println ("saved successfully");}} / proxy object public class StudentDaoProxy implements IStudentDao {/ / holds the reference private IStudentDao target; public StudentDaoProxy (IStudentDao target) {this.target = target of the target object } / / add transaction control public void save () {System.out.println ("start transaction"); target.save (); / / execute the target object's method System.out.println ("commit transaction") before and after the target function object method;}} public static void main (String [] args) {/ / create the target object StudentDao target = new StudentDao () / / create the proxy object, pass the target object to the proxy object, and establish the proxy relationship StudentDaoProxy proxy = new StudentDaoProxy (target); / / execute the proxy method proxy.save ();} dynamic proxy

Spring AOP uses dynamic proxies, that is, proxy classes are dynamically created by JVM while the program is running.

In the case of static proxies, the StudentDaoProxy class is custom and compiled before the program runs.

Dynamic proxies, proxy classes are not defined in the Java code, but are dynamically generated at run time according to our "instructions" in the Java code.

How to "instruct" JDK to generate proxy classes dynamically?

A Proxy class and an InvocationHandler interface are provided in the java.lang.reflect package of Java, through which dynamic proxy objects can be generated:

1. Define an InvocationHandler class and put the logic that needs to be extended into this class.

For example, the following example simulates adding transaction control:

Public class MyInvocationHandler implements InvocationHandler {private Object obj; public MyInvocationHandler (Object obj) {this.obj=obj;} @ Override public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {System.out.println ("start transaction"); Object result = method.invoke (obj, args); System.out.println ("start transaction"); return result;}}

two。 Create proxy objects dynamically using Proxy#newProxyInstance

Public static void main (String [] args) {/ / create the target object StudentDao IStudentDao stuDAO = new StudentDao (); / / create the MyInvocationHandler object InvocationHandler handler = new MyInvocationHandler (stuDAO); / / use Proxy.newProxyInstance to dynamically create the proxy object stuProxy IStudentDao stuProxy = (IStudentDao) Proxy.newProxyInstance (stuDAO.getClass (). GetClassLoader (), stuDAO.getClass (). GetInterfaces (), handler); / / use the proxy object method stuProxy.save ();}

The advantage of a dynamic proxy is that it is easy to uniformly handle the functions of the proxy class without having to modify the methods in each proxy class.

Spring implements the method-level enhancement of the class through dynamic proxy, that is, the proxy class of the target object is dynamically generated, and the interceptor is set in the method of the proxy class, and the function of the proxy method is enhanced by executing the logic in the interceptor, thus realizing AOP.

This is the end of this article on "what are the design patterns used in the Java Spring framework?". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report