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 in Spring?

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Today, I will talk to you about the specific design patterns in Spring, which may not be well understood by many people. in order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.

There are nine design patterns commonly used in spring. Let's give an example.

Simple factory model

Also known as the static factory method (StaticFactory Method) pattern, but it is not one of the 23 GOF design patterns.

The essence of the simple factory pattern is that a factory class dynamically decides which product class should be created based on the parameters passed in.

The BeanFactory in spring is the embodiment of the simple factory pattern. The bean object is obtained according to the identity passed in *, but whether to create this object after passing parameters or before passing parameters depends on the specific situation. The configuration is to create an itxxzBean in the HelloItxxz class.

Hello! This is singleton Beanned value > Hello! This is itxxzBean! Value >

Factory method model

Usually, the application directly uses new to create new objects. In order to separate the creation and use of the object, the factory mode is adopted, that is, the application hands over the responsibility of object creation and initialization to the factory object.

In general, applications have their own factory objects to create bean. If the application's own factory objects are handed over to Spring management, then Spring manages not the normal bean, but the factory Bean.

Take the static method in the factory method as an example to explain:

Import java.util.Random; public class StaticFactoryBean {public static Integer createRandom () {return new Integer (new Random (). NextInt ());}}

To create a config.xm configuration file and put it into the Spring container to manage, you need to specify the static method name through factory-method:

Test:

Public static void main (String [] args) {/ / returns a random number when calling getBean (). If no factory-method is specified, the instance of StaticFactoryBean will be returned, that is, the instance of factory Bean XmlBeanFactory factory = new XmlBeanFactory (new ClassPathResource ("config.xml")); System.out.println ("I am the instance created by IT learner: + factory.getBean (" random "). ToString ();}

Singleton mode

Ensure that there is only one instance of a class and provide a global access point to it.

The singleton pattern in spring completes the second half of the sentence, which provides a global access point, BeanFactory. However, the singleton is not controlled at the constructor level, because spring manages arbitrary java objects.

Core cue point: the default bean under Spring is singleton. You can use singleton= "true | false" or scope= "?" To specify.

Adapter mode

In the Aop of Spring, the Advice (notification) is used to enhance the functionality of the proxied class. The principle of Spring to achieve this AOP function is to use the proxy mode (1. JDK dynamic proxy. 2. CGLib bytecode generation technology agent. ) to enhance the aspect of the class at the method level, that is, generate the proxy class of the proxy class, and set the interceptor before the method of the proxy class, enhance the function of the proxy method by executing the heavy content of the interceptor, and realize aspect-oriented programming.

Adapter class interface: Target

Public interface AdvisorAdapter {boolean supportsAdvice (Advice advice); MethodInterceptor getInterceptor (Advisor advisor);} MethodBeforeAdviceAdapter class, Adapter class MethodBeforeAdviceAdapter implements AdvisorAdapter, Serializable {public boolean supportsAdvice (Advice advice) {return (advice instanceof MethodBeforeAdvice);} public MethodInterceptor getInterceptor (Advisor advisor) {MethodBeforeAdvice advice = (MethodBeforeAdvice) advisor.getAdvice (); return new MethodBeforeAdviceInterceptor (advice);}}

Wrapper mode

We encountered such a problem in our project: our project needs to connect to multiple databases, and different customers will access different databases according to their needs in each visit. In the past, we always configured a data source in the spring and hibernate frameworks, so the dataSource property of sessionFactory always points to this data source and is constant, and all DAO access the database through this data source when using sessionFactory.

But now, due to the needs of the project, our DAO has to switch among multiple data sources when accessing sessionFactory, so the problem arises: how to enable sessionFactory to dynamically switch between different data sources according to the needs of customers when performing data persistence? Can we solve it with a few modifications under the framework of spring? Are there any design patterns that can be used?

The first thought is to configure all the dataSource in the applicationContext of spring. These dataSource may be of different types, such as different databases: Oracle, SQL Server, MySQL, etc., or different data sources: such as org.apache.commons.dbcp.BasicDataSource provided by apache, org.springframework.jndi.JndiObjectFactoryBean provided by spring, and so on. Then sessionFactory sets the dataSource property to a different data source according to each request of the customer to achieve the purpose of switching the data source.

The wrapper pattern used in spring has two representations on class names: one is that the class name contains Wrapper, and the other is that the class name contains Decorator. Basically, you add some additional responsibilities to an object dynamically.

Agent mode

Provide a proxy for other objects to control access to this object. It is structurally similar to the Decorator pattern, but Proxy is a control, more like a limitation of functionality, while Decorator is an added responsibility.

Spring's Proxy pattern is reflected in aop, such as JdkDynamicAopProxy and Cglib2AopProxy.

Observer mode

Define an one-to-many dependency between objects. When the state of an object changes, all objects that depend on it are notified and updated automatically.

The common place of Observer pattern in spring is the implementation of listener. Such as ApplicationListener.

Strategy mode

Define a series of algorithms, encapsulate them one by one, and make them interchangeable. This mode allows the algorithm to change independently of the customers who use it.

Strategy schema is used in spring when instantiating objects.

The following code in SimpleInstantiationStrategy illustrates the use of policy mode:

Template method mode

Define the skeleton of an algorithm in an operation and defer some steps to a subclass. Template Method enables subclasses to redefine certain steps of an algorithm without changing the structure of the algorithm.

Template Method schemas generally need to be inherited. Here I want to explore another understanding of Template Method. JdbcTemplate in spring does not want to inherit this class when using this class, because there are too many methods in this class, but we still want to use the stable, public database connections that JdbcTemplate already has, so what do we do? We can extract the changes and pass them into the JdbcTemplate method as a parameter. But the change is a piece of code, and this code uses variables in JdbcTemplate. What shall I do? Then let's use the callback object.

Define a method to manipulate variables in JdbcTemplate in this callback object, and let's implement this method and focus on the changes here. Then we pass the callback object to JdbcTemplate, which completes the call. This may be another implementation that Template Method does not need to inherit.

The following is a concrete example:

Execute method in JdbcTemplate

JdbcTemplate executes the execute method

After reading the above, do you have any further understanding of the design patterns in Spring? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

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