Home  >  Article  >  Java  >  What are the design patterns used by Spring?

What are the design patterns used by Spring?

angryTom
angryTomOriginal
2020-02-14 15:06:373400browse

What are the design patterns used by Spring?

What are the design patterns used by Spring

1. Simple Factory Pattern

is also called 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 determines which product class should be created based on the incoming parameters.

The BeanFactory in spring is the embodiment of the simple factory pattern. The bean object is obtained according to a unique identifier, but whether it is created after the parameters are passed in or before the parameters are passed in depends on the specific situation. Certainly. The following configuration creates an itxxzBean in the HelloItxxz class.

<beans>  
    <bean id="singletonBean" class="com.itxxz.HelloItxxz">
         <constructor-arg>
            <value>Hello! 这是singletonBean</value>  
         </constructor-arg>
    </ bean>
    <bean id="itxxzBean" class="com.itxxz.HelloItxxz"  singleton="false">  
         <constructor-arg>     
             <value>Hello! 这是itxxzBean! </value> 
         </constructor-arg> 
    </bean>
</beans>

Recommended learning: What is Spring?

2. Factory method pattern

Usually the application directly uses new to create a new object. In order to separate the creation and use of the object, a factory is used. Pattern, that is, the application hands over the creation and initialization responsibilities of objects to the factory object.

Generally, the application has its own factory object to create beans. If the application's own factory object is handed over to Spring for management, then Spring will not manage ordinary beans, but factory beans.

Let’s 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());   
    }
}

Create a config.xm configuration file and incorporate it into the Spring container for management. You need to specify the static method through factory-method. Name:

<bean id="random"class="example.chapter3.StaticFactoryBean" factory-method="createRandom" scope="prototype"/>

Test:

public static void main(String[] args) {
    //调用getBean()时,返回随机数.如果没有指定factory-method,会返回StaticFactoryBean的实例,即返回工厂Bean的实例  
    XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("config.xml"));    
    System.out.println("我是IT学习者创建的实例:"+factory.getBean("random").toString());
}

3. Singleton mode

ensures that a class has only one instance and provides a global access to it access point. The singleton mode in spring completes the second half of the sentence, that is, it provides the global access point BeanFactory. But there is no singleton control from the constructor level, because spring manages arbitrary java objects.

Core tip: The default beans under Spring are all singletons, which can be specified by singleton="true|false" or scope="?".

4. Adapter pattern

In Spring's Aop, Advice (notification) is used to enhance the functionality of the proxy class. The principle of Spring's implementation of this AOP function is to use the proxy mode (1. JDK dynamic proxy. 2. CGLib bytecode generation technology proxy.) to enhance the method-level aspects of the class, that is, generate the proxy class of the proxy class, and Set an interceptor before the method of the proxy class, and enhance the function of the proxy method by executing the important content of the interceptor, realizing aspect-oriented programming.

Adapter class interface: Target

public interface AdvisorAdapter {
    boolean supportsAdvice(Advice advice);  
    MethodInterceptor getInterceptor(Advisor advisor);
}

MethodBeforeAdviceAdapter class,

Adapterclass 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); 
    }
}

5, wrapper mode

Recommendation: spring Chinese Manual

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 during each visit. database. In the past, we always configured a data source in the spring and hibernate frameworks, so the dataSource attribute of sessionFactory always pointed to this data source and remained unchanged. All DAOs access the database through this data source when using sessionFactory.

But now, due to the needs of the project, our DAO has to constantly switch between multiple data sources when accessing sessionFactory. The question arises: how to make sessionFactory perform data persistence according to the Can customers dynamically switch between different data sources according to their needs? Can we solve it with a few modifications under the spring framework? Are there any design patterns that can be utilized?

First think of configuring all dataSources in spring's applicationContext. These dataSources may be of various types, such as different databases: Oracle, SQL Server, MySQL, etc., or they may be different data sources: such as org.apache.commons.dbcp.BasicDataSource provided by apache, or org provided by spring. springframework.jndi.JndiObjectFactoryBean etc. Then sessionFactory sets the dataSource attribute to a different data source according to each customer request to achieve the purpose of switching data sources.

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

6. Proxy mode

Provides a proxy for other objects to control access to this object. Structurally, it is similar to the Decorator pattern, but Proxy is control, more like a restriction of functions, while Decorator is to increase responsibilities. Spring's Proxy mode is reflected in aop, such as JdkDynamicAopProxy and Cglib2AopProxy.

7. Observer pattern

Defines a one-to-many dependency relationship between objects. When the state of an object changes, all objects that depend on it Objects are notified and updated automatically. The most commonly used place for the Observer pattern in spring is the implementation of listener. Such as ApplicationListener.

8. Strategy mode

Define a series of algorithms, encapsulate them one by one, and make them interchangeable. This pattern allows the algorithm to change independently of the client using it. Strategy mode is used in spring when instantiating objects. The following code in SimpleInstantiationStrategy illustrates the use of strategy mode:

What are the design patterns used by Spring?

9. Template method mode

Define the skeleton of an algorithm in one operation, while deferring some steps to subclasses. Template Method allows subclasses to redefine certain specific steps of an algorithm without changing the structure of the algorithm.

Template Method pattern generally needs to be inherited. Here I want to explore another understanding of Template Method. When using JdbcTemplate in spring, we don’t want to inherit this class because this class has too many methods, but we still want to use the stable and public database connection that JdbcTemplate has. So what should we do? We can extract the changes and pass them into the JdbcTemplate method as a parameter. But what changes is a piece of code, and this code will use variables in JdbcTemplate. what to do? Then let's use callback objects.

(Related video tutorial sharing: java video tutorial)

Define a method for manipulating variables in JdbcTemplate in this callback object. To implement this method, just The changes are concentrated here. Then we pass this callback object to JdbcTemplate to complete the call. This may be another way to implement Template Method without inheritance.

The following is a specific example: execute method in JdbcTemplate

JdbcTemplate executes execute method

What are the design patterns used by Spring?

The above is the detailed content of What are the design patterns used by Spring?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:SpringMVC workflowNext article:SpringMVC workflow