Application of detailed design pattern in spring

Source: Internet
Author: User
Tags aop wrapper
Design model as a pillow in the work of learning, but often in the use of the awkward situation, is not that we often forget, but have no memory.

Today, crabs in the IT Learner's website on the intrinsic value of design patterns to do some discussion, and take spring as an example to explain, only to appreciate the idea of its design, can be applied to work in the "invisible."

Spring as the industry's classic framework, both in architectural design and in code writing, is 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 have examples:

The first: Simple factory

Also known as the Static factory approach (Staticfactory method) mode, but it does not belong to one of 23 gof design patterns.
The essence of a simple factory pattern 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 a simple factory pattern that obtains a bean object based on passing in a unique identity, but whether it is created or passed in before the parameter is passed in depends on the specific circumstances. The following configuration is to create a itxxzbean in the Helloitxxz class.
<beans> <bean id= "Singletonbean" class= "Com.itxxz.HelloItxxz" > <constructor-arg> <value>hello! This is singletonbean!value> </constructor-arg> </bean> <bean id= "Itxxzbean" class= Xxz. Helloitxxz "singleton=" false "> <constructor-arg> <value>hello! This is itxxzbean!. value> </constructor-arg> </bean> </beans>
Second: Factory methods (Factory method)

It is common for applications to create new objects directly using new, in order to separate the creation and use of objects, in Factory mode, where the application takes the creation and initialization responsibility of the object to the factory object.
In general, the application has its own factory object to create the bean. If you give the application's own factory object to spring management, then spring manages not the normal bean, but the factory bean.
The crab takes 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 (). N        Extint ()); } }
To build a CONFIG.XM configuration file to be managed by incorporating it into the spring container, you need to specify the static method name by Factory-method
<bean id= "random" class= "Example.chapter3.StaticFactoryBean"
The factory-method= "Createrandom"//createrandom method must be static in order to find
Scope= "Prototype"/>
Test:
public static void Main (string[] args) {

When Getbean () is invoked, a random number is returned. If no factory-method is specified, an instance of Staticfactorybean is returned, which returns an instance of the factory bean
Xmlbeanfactory factory = new Xmlbeanfactory (New Classpathresource ("Config.xml"));
System.out.println ("I am an example created by an IT learner:" +factory.getbean ("random"). ToString ()); The third type: Single case mode (Singleton)

Guarantees that a class has only one instance and provides a global access point to access it.
The single example pattern in spring completes the second half of the sentence, which provides a global access point beanfactory. However, there is no control from the constructor level for a single example, because spring manages any Java object.
Core hint point: The default Bean under Spring is singleton and can be singleton= "True|false" or "scope=". "To specify

Type fourth: Adapters (Adapter)

In spring's AOP, the advice (notification) is used to enhance the functionality of the proxy class. The rationale for spring's implementation of this AOP function is to use proxy mode (1, JDK dynamic proxy). 2, Cglib byte code generation technology agent. The method-level aspect enhancement of the class, that is, generating the proxy class of the proxy class, and setting the interceptor before the method of the proxy class, enhances the function of the proxy method by executing the content of the interceptor, and implements the facet-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 {Pub       Lic boolean supportsadvice (Advice Advice) {return Advice instanceof); Public Methodinterceptor Getinterceptor (Advisor Advisor) {Methodbeforeadvice advice = (Methodbefore       Advice) Advisor.getadvice ();       return new Methodbeforeadviceinterceptor (advice); }   }
Type Fifth: packaging (decorator)

The problem with our projects is that our projects need to connect to multiple databases, and different customers visit different databases as needed on each visit. We used to always configure a data source in the spring and hibernate frameworks, so the Sessionfactory datasource attribute always points to this data source and is constant. All DAO accesses the database through this data source when using Sessionfactory. But now, because of the needs of the project, our DAO will have to switch on multiple data sources when we visit sessionfactory, the problem arises: how to make the sessionfactory to dynamically switch different data sources according to the customer's requirement when performing data persistence. Can we fix it with a little bit of change under Spring's framework? Is there any design pattern you can use?
The first thought is to configure all the DataSource in spring's applicationcontext. These datasource may be of various types, such as different databases: Oracle, SQL Server, MySQL, and possibly different data sources: Apache, for example. Provides Org.apache.commons.dbcp.BasicDataSource, spring-provided org.springframework.jndi.JndiObjectFactoryBean, etc. Sessionfactory then sets the DataSource property to a different data source based on each request of the customer, to reach the destination of the switching data source.
The wrapper pattern used in spring has two manifestations on the class name: one that contains wrapper in the class name and one that contains decorator in the class name. Basically, you add some extra responsibility to an object dynamically.

Sixth: Agent (proxy)

Provides a proxy for other objects to control access to this object.
The structure is similar to the decorator pattern, but the proxy is control, more like a function restriction, and decorator is an increase in responsibility.
Spring's proxy pattern is embodied in AOP, such as Jdkdynamicaopproxy and Cglib2aopproxy.

Type seventh: Observer (Observer)

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

Eighth: Strategy (strategy)

Define a series of algorithms that encapsulate them each, and make them interchangeable. This mode allows the algorithm to vary independently from the customer who uses it.
Strategy mode is used when instantiating objects in spring
The following code in Simpleinstantiationstrategy illustrates the use of the policy pattern:

Nineth: Template Methods (Template method)

Defines the skeleton of an algorithm in an operation, and delays some steps into subclasses. Template method enables subclasses to redefine certain steps of the algorithm without altering the structure of an algorithm.
The Template method pattern 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 jdbctemplate existing stable, common database connection, then what do we do? We can extract the changed things as a parameter into the JdbcTemplate method. But the thing that changes 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 and focus the changes here. We then pass the callback object to the JdbcTemplate, which completes the call. This may be another way to implement template method without inheriting it.

The following is a specific example:
The Execute method in JdbcTemplate

JdbcTemplate Execute Execute method


Article starts with it learners
Reprint please indicate the source: http://www.itxxz.com/a/javashili/tuozhan/2014/0601/7.html

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.