What design patterns are used in spring?

Source: Internet
Author: User

Design mode as a work learning in the Pillow book, but often in the hard to say no awkward situation, nor we often forget, but have no memory.

Spring is the industry's classic framework, both in terms of architectural design and coding, as an example of the line. Well, don't talk much, start today's content.

There are nine types of design patterns commonly used in spring, and we illustrate:

The first type: Simple Factory

Also called the Static Factory method (Staticfactory) mode, but is not part of one of the 23 gof design patterns.

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

The beanfactory in spring is the embodiment of the simple factory pattern, which obtains the Bean object based on the passing of a unique identity, but whether it is created before the parameter is passed in or passed in to the parameter, depending on the situation. The following configuration is to create a itxxzbean in the Helloitxxz class.

<Beans>    <BeanID= "Singletonbean"class= "Com.itxxz.HelloItxxz">      <Constructor-arg>      <value>hello!, this is singletonbean!value> .</Constructor-arg>    </Bean>    <BeanID= "Itxxzbean"class= "Com.itxxz.HelloItxxz"Singleton= "false">      <Constructor-arg>      <value>hello!, this is itxxzbean! value> .</Constructor-arg>    </Bean></Beans>

The second type: Factory method

Typically, a new object is created by the application directly using new, in order to separate the creation and use of the object, in Factory mode, where the application creates and initializes the object to the factory object.

In general, the application has its own factory object to create the bean. If the application's own factory object is given to spring management, then spring manages not the normal bean, but the factory bean.

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

Import Java.util.Random;  Public class Staticfactorybean {  publicstatic  Integer createrandom () {       return  New Integer (new  Random (). Nextint ());}   }

A CONFIG.XM configuration file is built to be managed by the spring container, and the static method name needs to be specified by Factory-method

<IDclass= "Example.chapter3.StaticFactoryBean"  Factory-method= "Createrandom"  //createrandom method must be static to find scope= "Prototype" />

Test:

 Public Static void Main (string[] args) {  // call Getbean (), returns a random number. If no factory-method is specified, the        new is returned    Xmlbeanfactory (new classpathresource ("config + +")); System.out.println ("I am an instance of it learner creation:" +factory.getbean ("random"). toString ());}

The third type: Singleton mode (Singleton)

Ensure that a class has only one instance and provides a global access point to access it.
The singleton pattern in spring completes the second half of the sentence, which provides the global access point beanfactory. However, the Singleton is not controlled from the constructor level, because spring manages arbitrary Java objects.

Core Cue point: The default Bean under Spring is singleton and can be singleton= "True|false" or "scope="? "To specify

Fourth type: Adapter (Adapter)

In spring AOP, advice (notification) is used to enhance the functionality of the proxy class. Spring implements this AOP feature using the proxy mode (1, the JDK dynamic agent. 2, Cglib byte code generation technology agent. The method-level aspect enhancement of the class, that is, to generate the proxy class of the proxy class, and before the method of the proxy class, set the interceptor, through the execution of the content of the interceptor to enhance the function of the proxy method, the implementation of plane-oriented programming.

Adapter class Interface: Target

 Public InterfaceAdvisoradapter {BooleanSupportsadvice (Advice Advice); Methodinterceptor Getinterceptor (Advisor Advisor);}

Methodbeforeadviceadapter class, AdapterclassMethodbeforeadviceadapterImplementsAdvisoradapter, Serializable { Public BooleanSupportsadvice (Advice Advice) {return(AdviceinstanceofMethodbeforeadvice); }
   Publicmethodinterceptor getinterceptor (Advisor Advisor) {Methodbeforeadvice Advice=(Methodbeforeadvice) advisor.getadvice (); return NewMethodbeforeadviceinterceptor (advice); }
}

Fifth type: Wrapper

In our project, we encountered the problem of connecting multiple databases to our projects, and different clients accessing different databases as needed in each visit. We used to always configure a data source in the spring and hibernate frameworks, so the DataSource property of Sessionfactory always points to this data source and remains constant, All DAO uses this data source to access the database when Sessionfactory is used. But now, because of the needs of the project, our DAO in Access to Sessionfactory in the time of the various data sources have to constantly switch, the problem arises: how to let Sessionfactory in the implementation of data persistence, according to the needs of customers can dynamically switch different data sources? Can we fix this with a few changes in the spring framework? Are there any design patterns that can be used?

First think of configuring all the DataSource in spring's applicationcontext. These datasource may be of different types, such as different databases: Oracle, SQL Server, MySQL, and possibly different data sources: Apache, for example. Provided by Org.apache.commons.dbcp.BasicDataSource, spring-provided org.springframework.jndi.JndiObjectFactoryBean and so on. Sessionfactory then sets the DataSource property to a different data source based on each request of the customer to reach the purpose of switching the data source.

The wrapper pattern used in spring has two manifestations on the class name: one is that the class name contains wrapper, and the other is that the class name contains decorator. Basically, it's a dynamic way of adding some extra responsibilities to an object.

The Sixth type: Agent (proxy)

Provides a proxy for other objects to control access to this object. Structurally, the decorator model is similar, but the proxy is control, more like a function of limitations, and decorator is to increase responsibility.
Spring's proxy patterns are embodied in AOP, such as Jdkdynamicaopproxy and Cglib2aopproxy.

Seventh TYPE: Observer (Observer)

Defines a one-to-many dependency between objects, and when an object's state changes, all objects that depend on it are notified and automatically updated.
The common place for observer patterns in spring is the implementation of listener. such as Applicationlistener.

Eighth Type: Strategy (strategy)

Define a series of algorithms, encapsulate them one by one, and make them interchangeable with each other. This mode allows the algorithm to be independent of the customers who use it.
Use the strategy mode when instantiating objects in spring
In Simpleinstantiationstrategy, the following code illustrates the use of the policy pattern:

The Nineth type: Template method

Defines the skeleton of an algorithm in an operation, and delays some steps into subclasses. Template method allows subclasses to redefine some specific steps of the algorithm without altering the structure of an algorithm

Template method mode is generally required to inherit. Here we 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 for this class, but we still want to use the stable, common database connection that JdbcTemplate already have, so what do we do? We can pull things out of change as a parameter into the JdbcTemplate method. But the change is a piece of code, and this code uses the variables in the JdbcTemplate. What to do? Then let's use the callback object. In this callback object, we define a method to manipulate the variables in the JdbcTemplate, so that we can implement this method, we will focus on the things that have changed. We then pass this callback object to JdbcTemplate, which completes the call. This may be another way of implementing the template method, which does not require inheritance.

Here is a specific example:
The Execute method in JdbcTemplate

JdbcTemplate Execute Execute method

What design patterns are used in spring?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.