Common application Scenarios for Java design Patterns __java

Source: Internet
Author: User
Tags aop
Design Patterns in Java I/O 1. Adapter Mode

Adapter mode is to transform the interface of a class into another interface acceptable to the client, so that two classes that do not match two interfaces can work together. Often used when a project needs to refer to some open source frameworks to work together, there are interfaces for environmental information inside these frameworks that need to be introduced externally, but external interfaces do not necessarily match, in which case the adapter pattern is required to transform the interface.

Java I/O class libraries have many of these requirements, such as converting a string into byte data to a file, converting byte data into a data stream, and so on. Specifically, InputStreamReader and OutputStreamWriter are the embodiment of the adapter. InputStreamReader implements the reader interface and holds InputStream references, and its role is to fit inputstream to reader. The source role is the instance object represented by the InputStream, and the target role is the reader class. OutputStreamWriter is a similar way. 2. Decorator Mode

The role of the adorner is to make the decorated person more powerful, and the use of the same way before and after decoration. There are many different combinations of features in the Java I/O class library, and these different combinations of features are implemented using an adorner pattern. Taking FileInputStream as an example, its class structure is as follows:

Because Java I/O libraries require a variety of combinations of performance, if these performance are implemented using inheritance, then each combination requires a class, which causes a large number of rows to duplicate the occurrence of the class. If you use decorative mode, the number of classes will be greatly reduced, the performance of the duplication can be minimized. Therefore, the decorative pattern is the Java I/O library basic pattern. The introduction of decorative mode, resulting in increased flexibility and complexity. So when using the Java I/O library, it must be understood that the Java I/O library is composed of some basic raw stream processors and a decorative flow processor around them.
The InputStream class is in the form of an abstract component, and FileInputStream is a concrete component that implements all the methods of an abstract interface and holds a reference to the InputStream object. FileInputStream is a decorative class, and bufferinputstream is the specific implementation of this decorative class, it adds new functionality to InputStream, allowing InputStream read data to be stored in memory, thereby improving read performance. 3. The difference between fitting mode and decoration mode

The adaptation pattern is designed to handle inconsistencies in two of excuses, altering existing interfaces to match them.
The decoration mode is to add new functionality without changing the existing interface. second, the visitor pattern in the Javac

Javac is the Java language programming compiler. Full name javacompilation. The Javac tool reads the definitions of classes and interfaces written by the Java language and compiles them into a class file of byte code. Javac can implicitly compile some source files that are not mentioned in the command line. Use the-verbose option to track automatic compilation. When compiling a source file, the compiler often needs information about a type that it has not yet recognized. For each class or interface that is used, extended, or implemented in the source file, the compiler needs its type information. This includes classes and interfaces that are not explicitly mentioned in the source file, but that provide information through inheritance.
Javac's compilation process involves many syntactic analyses, all with a parser, semantic analyzer, and code generator, which requires multiple traversal of the syntax tree. However, each traversal of the syntax tree will be different processing action, this is how to achieve it. is designed by using the visitor pattern, each traversal is a visitor's execution process.
The visitor pattern can make the data structure and the operation of the data structure decoupled, make the operation of the data structure not need to modify the data structure, do not have to modify the original operation, and then define the new visitor implementation. Different audience pattern implementations are defined in different compile phases in Javac. Design Patterns in Tomcat 1, façade mode

The Tomcat design pattern is used a lot, because Tomcat has many components, each of which interacts with the data, and it's a good way to isolate the data with a façade design pattern.

As you can see, the Httprequestfacade class encapsulates the HttpRequest interface, can provide data, and the data accessed through Httprequestfacade is represented in Httpreauest, Usually encapsulated objects are set to private or PROTECTD to prevent direct access in the façade. 2. Observer Mode

Tomcat mode is also used in many places, and the lifecycle of the previous control component lifecycle is the embodiment of this pattern, as are the same principles for the creation of Servlet instances, session management, container, and so on. The following main look at the specific implementation of lifecycle. The
Lifecycle Observer pattern structure diagram is shown in the figure.

In the above structure diagram, Lifecyclelistener represents an abstract observer, which defines a lifecycleevent method, which is the method to execute when the theme changes. Serverlifecyclelistener represents the specific observer, which implements the method of Lifecyclelistener interface, which is the concrete implementation of this specific observer. The lifecycle interface represents an abstract theme that defines the method of managing the observer and the other methods it has to do. And Standardserver represents a specific theme that implements all the methods of an abstract theme. Here tomcat extends the observer by adding another two classes: Lifecyclesupport and lifecycleevent, which extend the observer's functionality as a helper class. Lifecycleevent allows you to define event categories, different events can be handled differently, and more flexible. Lifecyclesupport class agent of the subject of the management of multiple observers, this management will be taken out to unify the implementation, such as modified as long as modified Lifecyclesupport class on it, do not need to modify all the specific topics, because The actions of all the specific subjects to the observer are represented to the Lifecyclesupport class. This can be considered an improved version of the Observer model. 3, command design mode

The command mode in Tomcat is embodied between the connector and container components, and Tomcat as an application server will undoubtedly receive many requests, and how to allocate and execute these requests is a necessary function.
Below is an analysis of how Tomcat implements the command mode, and the following figure is a structure diagram of the Tomcat command pattern.

Connector as an abstract requester, httpconnector as a specific requestor. Httpprocessor as an order. Container as the abstract recipient of the command, containerbase as a concrete recipient. The client is the Application Server server component. Server first creates the command requester HttpConnector object, and then creates the command Httpprocessor object. The command object is then handed over to the command recipient Containerbase container to be processed, and the command is ultimately executed by Tomcat's container. Commands can come in queues, and container can also handle requests in different ways, such as HTTP1.0 protocols and HTTP1.1. 4. Responsibility chain Mode

One of the most easily discovered design patterns in Tomcat is the responsibility chain design pattern, which is also the basis for Tomcat's containe design, the entire container connected through a chain that always sends the request correctly to the Servlet that finally handles the request. This design pattern in Tomcat is completely used, and Tomcat's container setting is the responsibility chain mode, from engine to host to cortex, until wrapper passes the request through this chain.
iv. Design Patterns in spring 1. Simple Factory mode

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.kang.HelloItxxz" >
        <constructor-arg>
            <value>hello! This is singletonbean!value>
        </constructor-arg>
   </bean>

    <bean id= "Itxxzbean" Com.kang.HelloItxxz "
        singleton=" false ">
        <constructor-arg>
            <value>hello! This is itxxzbean! value>
        </constructor-arg>
    </bean>

</beans>
2. Factory method Mode

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.
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 to be managed by incorporating it into the spring container, you need to specify the static method name by Factory-method, and the Createrandom method must be static to find

<bean id= "random" class= "Example.chapter3.StaticFactoryBean" factory-method= "Createrandom"
Prototype "
/>
3. Single case mode

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. The default bean under Spring is singleton and can be singleton= "True|false" or "scope=". "To specify 4, Agent mode

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. 5, Template method mode

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. 6. Strategy Mode

There are a plethora of policy patterns in spring, and the so-called policy pattern is defined as the algorithm family, packaged separately, so that they can be converted to each other before, and this pattern is independent of the algorithm used by the client. Spring's transaction management mechanism is a typical policy pattern, and the spring transaction strategy is implemented through the Platformtransactionmanager interface, which is the core of the entire spring transaction. It is a highly abstract transaction strategy that does not depend on any specific transaction strategy, and it has a different implementation class for the underlying specific transaction strategy. Switching to different transaction policies is typically managed by the spring container, where the application is not coupled to a specific transaction API, and the application and persistence technology is separated from the transaction APIs without the need to be coupled to a particular implementation class. the template pattern in Springmvc

The so-called template pattern is to define the skeleton of an algorithm in an operation, and delay some steps into subclasses. Springmvc a lot of holes in the process of ensuring the stability of the entire framework, and these are called template methods that are freely specified to ensure flexibility, and many of the next best practices are based on this design pattern. For example, in the following code doresolveexception (..) It's just a hole, subclass method Doresolveexception (..) You can define how exceptions are handled specifically.

Public Modelandview resolveexception (httpservletrequest request, httpservletresponse response, Object handler,
        Exception ex) {
    if (Shouldapplyto (request, Handler)) {
        logexception (ex, request);
        Prepareresponse (ex, response);
        return doresolveexception (Request, response, Handler, ex);
    else {return
        null;
    }
}

Protected abstract Modelandview doresolveexception (httpservletrequest request, httpservletresponse response,
        Object handler, Exception ex);

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.