Source: author: crab itxxz.com/a/javashili/tuozhan/2014/0601/7.htmlCopy the code

As a pillow book in work and study, design patterns are often in the awkward situation of saying no to them frequently. It is not that we often forget, but that we have no memory all the time. As a classic framework in the industry, Spring is a model for both architectural design and code writing.

All right, without further ado, let’s get started. There are nine commonly used design patterns in Spring, which we illustrate.

No longer will I be afraid of being asked what design patterns Spring uses.

Simple Factory model

Also known as the StaticFactory Method pattern, but 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 an embodiment of the simple factory pattern. Bean objects are obtained by passing in a unique identifier, but whether this is created after or before the parameters are passed in depends on the case. 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! This is itxxzBean! </value> </constructor-arg> </bean></beans>Copy the code

Factory method pattern

Typically, applications create new objects directly using New. In order to separate the creation and use of objects, the factory pattern is adopted, in which applications delegate the creation and initialization of objects to factory objects.

Typically, applications have their own factory objects to create beans. If Spring manages the application’s own factory objects, Spring manages factory beans instead of ordinary beans.

Let’s take static methods in the factory method as an example:

import java.util.Random; public class StaticFactoryBean { public static Integer createRandom() { return new Integer(new Random().nextInt()); }}Copy the code

To create a config.xm configuration file and add it to the Spring container for management, use factory-method to specify static method names:

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

Testing:

Public static void main(String[] args) {// Returns a random number when getBean() is called. If factory-method is not specified, an instance of StaticFactoryBean is returned, that is, an instance of the factory Bean XmlBeanFactory Factory = new XmlBeanFactory(new) ClassPathResource("config.xml")); System.out.println(" I am an instance created by IT learners :"+factory.getBean("random").toString()); }Copy the code

The singleton pattern

Ensure that a class has only one instance and provide a global access point to access it. The singleton pattern in Spring completes the latter part of the sentence, providing a global access point to the BeanFactory. But there is no control over singletons at the constructor level, because Spring manages arbitrary Java objects.

Core tip: Spring under the default beans are singleton, can through the singleton = “true | false” or scope = “?” To specify.

Adapter mode

In Spring’s Aop, Advice is used to enhance the proxyed class. Spring implements this AOP functionality using the proxy pattern (1) JDK dynamic proxies. 2. CGLib bytecode generation technology agent. The class method level section enhancement, that is, the generation of proxy class proxy class, and in front of the proxy class method, set the interceptor, through the implementation of the interceptor heavy content enhanced the function of the proxy method, the realization of the section 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); }}Copy the code

Wrapper pattern

One problem we encountered in our project was that we needed to connect to multiple databases, and different customers would access different databases on each visit as needed. Spring and hibernate frameworks have always configured a dataSource, so the dataSource property of the sessionFactory always points to the dataSource and remains constant. All daos use the sessionFactory dataSource to access the database.

However, due to the needs of the project, our DAO has to constantly switch between multiple data sources when accessing the sessionFactory. The problem arises: how can sessionFactory dynamically switch between different data sources when performing data persistence according to the needs of customers? Can we fix this in the Spring framework with a few modifications? Are there any design patterns that can be leveraged?

The first thing to think about is configuring all dataSource in Spring’s applicationContext. These datasources may be of various types, such as different databases: Oracle, SQL Server, MySQL, etc., or different data sources: Such as provided by the apache org.apache.com mons. DBCP. BasicDataSource, spring provides org. Springframework. Jndi. JndiObjectFactoryBean, etc. SessionFactory then sets the dataSource property to a different dataSource according to each request of the customer, in order to achieve the purpose of switching data sources.

The Wrapper pattern used in Spring has two representations on class names: one with a Wrapper in the class name and one with a Decorator in the class name. Basically, adding some extra responsibilities to an object on the fly.

The proxy pattern

Provide a proxy for other objects to control access to that object. The structure is similar to the Decorator pattern, but a Proxy is control, more like a restriction on functionality, whereas a Decorator adds responsibility. Spring’s Proxy pattern is reflected in AOP, such as JdkDynamicAopProxy and Cglib2AopProxy.

Observer model

Defines a one-to-many dependency between objects in which all dependent objects are notified and automatically updated when an object’s state changes. A common place in Spring for the Observer pattern is the listener implementation. Such as ApplicationListener.

The strategy pattern

Define a set of algorithms, encapsulate them one by one, and make them interchangeable. This pattern allows the algorithm to change independently of the customers using it. Spring at the time of instantiation objects used in the Strategy pattern in SimpleInstantiationStrategy has the following code illustrates the use of the Strategy pattern:

Template method pattern

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

The Template Method pattern is generally inherited. Here I want to explore another understanding of the Template Method. JdbcTemplate in Spring does not want to inherit from this class because it has too many methods, but we still want to use the stable, common database connection that JdbcTemplate already has. So what do we do? We can pull out the change and pass it as a parameter to the JdbcTemplate method. But what changes is a piece of code, and that code uses variables in the JdbcTemplate. How to do? So let’s use callback objects.

Define a method in the callback object that manipulates the variables in the JdbcTemplate, and we implement this method to concentrate the changes here. We then pass the callback object to the JdbcTemplate to complete the call. This might be another way to implement the Template Method that doesn’t need to inherit.

Here’s a concrete example: the execute method in JdbcTemplate

JdbcTemplate executes the execute method

Welcome to GitHub. Welcome to Star.

What is a regular Expression

Learn more about IO in Java

Deep concurrency Issue 006: Proper usage posture for Java thread pools

– MORE | – MORE excellent articles

  • 35 years old programmer, the first day after the year was fired

  • 2019 Spring Recruitment is about to start, all you care about is here!

  • Netty: How to write a web container

  • What is DNS? What is DNS contamination? What is DNS hijacking?

If you enjoyed this article.

Please long press the QR code to follow Hollis

Forwarding moments is the biggest support for me.