Dead Knock Spring AOP Series 5: The use of design patterns in AOP

Source: Internet
Author: User

Dead Knock Spring AOP Series 3: Parsing bean processor Defaultadvisorautoproxycreator dead Spring AOP Series 2: Parsing bean processor Beannameautoproxycreator dead Knock Spring AOP Series 1: Programmatic implementation of AOP

Dead Spring AOP Series 4: Anatomy of the AOP schema approach

The principle of AOP should be mastered by the previous dead knock. Annotation configuration AOP, there is no need to speak again. Annotation and XML Schema two ways, only the way the declaration is different, the others are the same.

Spring as a popular framework technology, its code design is very worthy of reference. From coding style to design pattern, there are a lot of points we learn. This article focuses on the use of design patterns in the AOP framework, with a review of several classic design patterns.

Using design patterns, nothing is more than multiplexing + decoupling. Quoting Mr Lu Xun's sentence, "There is no pattern in the world, the use of more people, there will be a pattern." In the process of learning mode, I often learn to forget, forget to learn, a lot of effort, has been pointless. Finally, with the accumulation of experience, have a little knowledge of their own. At first, I put emphasis on the class diagram, and the role of memory, feel very simple, feeling after a simple combination, to achieve system decoupling, scalability, the role of design patterns have a knowledge, but so easy to forget. Slowly, I found that the pattern of learning, is the scene and pattern matching process, we need to measure, often a function, there are multiple models can be achieved, which will test our thinking. In fact, often a lot of excellent framework technology, will also occur patterns change, this is a truth.

The main contents include

    1. The use of policy patterns in AOP

    2. The use of template patterns in AOP

    3. The use of responsibility chain model in AOP

    4. The use of adapter mode in AOP

    5. The use of bridging mode in AOP



1 use of policy patterns in AOP

1.1 Pattern structure

650) this.width=650; "src=" Http://design-patterns.readthedocs.io/zh_CN/latest/_images/Strategy.jpg "alt=" Strategy.jpg "height=" 329 "width=" 764 "/>

    • Context: Environment class

    • Strategy: Abstract Policy class

    • Concretestrategy: Specific policy classes


1.2 for use in spring

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M02/82/61/wKioL1dTnKKCDewWAAA4czN6c5I498.png "title=" 1.png " alt= "Wkiol1dtnkkcdewwaaa4czn6c5i498.png"/>


With the Rose7 drawing, there is a problem with the line implemented by the interface.

Advantages of the policy model

    • The policy model provides the perfect support for the "open and close principle", which allows users to choose an algorithm or behavior without modifying the original system, or to add new algorithms or behaviors flexibly.

    • The policy pattern provides a way to manage the associated algorithm families.

    • The policy pattern provides a way to replace the inheritance relationship.

    • Use the policy mode to avoid using multiple conditional transfer statements.

By using the policy mode, it is easier and more flexible to implement the substitution of proxy generation mode.

Simply look at the code snippet for the Environment class Defaultaopproxyfactory

Public aopproxy createaopproxy (Advisedsupport config)  throws AopConfigException  {   if  (config.isoptimize ()  | |  config.isproxytargetclass ()  | |  hasnousersuppliedproxyinterfaces (config))  {      Class  Targetclass = config.gettargetclass ();      if  (targetClass  == null)  {         throw new  Aopconfigexception ("targetsource cannot determine target class: "  +                 "Either an interface  or a target is required for proxy creation. ");       }      if  (Targetclass.isinterface ())  {         return new&nbsp Jdkdynamicaopproxy (config);       }      return  cglibproxyfactory.createcglibproxy (config);   }   else {       return new jdkdynamicaopproxy (config);    }}

1.3 Summary

    • A series of algorithms are defined in the policy mode, encapsulating each algorithm and allowing them to replace each other . The policy pattern makes the algorithm independent of the customers that use it, also known as the policy model. The policy mode is an object-based behavior pattern.

    • The policy pattern consists of three roles: the environment class can adopt various strategies to solve a problem, maintain a reference instance to the abstract policy class in the Environment class, the abstract policy class declares the abstract method for the supported algorithm, is the parent class of all policy classes, and the specific policy class implements the algorithm defined in the abstract policy class.

    • The strategy pattern is the encapsulation of the algorithm, which divides the responsibility of the algorithm and the algorithm itself , delegating to different object management. The strategy pattern typically encapsulates a series of algorithms into a set of policy classes as subclasses of an abstract policy class.

    • The main advantage of the strategy model lies in the perfect support of the "open and close principle", which can replace the algorithm or add new algorithm on the basis of not modifying the original system, it manages the algorithm family well, improves the reusability of the code, is a substitution inheritance, avoids the multiple conditional transfer statement realization Way , the disadvantage is that the client must know all the policy classes and understand the differences, and at the same time increase the number of classes in the system to some extent, there may be many policy classes.

    • The application of the policy mode includes: In a system there are many classes, they are only the difference between their behavior , using the policy model can be used to dynamically let an object in many behaviors to choose a behavior; a system needs to dynamically select one of several algorithms ; Avoid using multiple conditional selection statements that are difficult to maintain; you want to encapsulate the algorithm and the associated data structure in a specific policy class.



2. The use of template patterns in AOP

2.1 Template method mode
    • Design principle : Destroy the Richter scale replacement, reflect the function multiplexing

    • Common Scenario : A batch of subclasses has the ability to extract common algorithmic skeletons

    • usage probability : 80%

    • complexity : Medium to Low

    • Change Point : The concrete implementation of each step in the algorithm skeleton

    • Select key : Whether the algorithm skeleton is solid

    • Inverse scales : None

650) this.width=650; "src=" Http://pic002.cnblogs.com/images/2012/155937/2012070917340125.png "alt=" 2012070917340125.png "height=" 470 "width=" 572 "/>

Role

Abstract class (AbstractClass): The template method is implemented, and the skeleton of the algorithm is defined.

Concrete Class (Concreteclass): Implements the abstract method in the abstract class, has completed the complete algorithm.

2.2 Pattern Summary
Advantages
The template method pattern removes duplicate code from subclasses by moving the invariant behavior to the superclass.
Subclasses implement some of the details of the algorithm, which facilitates the expansion of the algorithm.
By invoking the subclass implementation of a parent class, the new behavior is added through the subclass extension, which conforms to the open-close principle.
Disadvantages
Each different implementation needs to define a subclass, which causes the number of classes to increase and the design to be more abstract.
Applicable scenarios
In some classes of algorithms, the same method is used, resulting in code duplication.
Control subclass extensions, subclasses must adhere to algorithmic rules.

2.3 Use in spring

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M02/82/63/wKiom1dTp8HwVNiFAABiKqgjRf0437.png "title=" 2.png " alt= "Wkiom1dtp8hwvnifaabikqgjrf0437.png"/>

AOP-related proxy beanpostprocessor. Sub-class implementations provide Annotation,schema, etc., respectively, Implementation templates are Abstractautoproxycreator.getadvicesandadvisorsforbea and abstractadvisorautoproxycreator.findeligibleadvisor and other places.

Take Abstractadvisorautoproxycreator.findeligibleadvisor code as an example

Protected list<advisor> findeligibleadvisors (Class beanclass, String beanname) {list<advisor>   Candidateadvisors = Findcandidateadvisors ();   list<advisor> eligibleadvisors = findadvisorsthatcanapply (candidateadvisors, BeanClass, beanName); Extendadvisors (eligibleadvisors);//subclasses can override if (!eligibleadvisors.isempty ()) {eligibleadvisors = Sortadvisors (Eligib leadvisors);//subclasses can overwrite} return eligibleadvisors;}

After parsing the code, template mode is used in many places in the Abstractautoproxycreator tree.

3. The use of the responsibility chain model in AOP

3.1 Responsibility chain pattern structure

Design principle: Follow Dimitri
Common scenario: one or several collaborative processing of multiple objects is required for processing a request
Usage probability: 15%
Complexity: Medium
Change point: The length and order of the processing chain
Select key: Whether each request requires a processing opportunity for each processed object
Inverse scales: None

650) this.width=650; "Src=" http://e.hiphotos.baidu.com/baike/c0%3Dbaike80%2C5%2C5%2C80%2C26/sign= 962b28214dfbfbedc8543e2d19999c53/b7003af33a87e950f9ae4a7216385343fbf2b477.jpg "alt=" b7003af33a87e950f9ae4a7216385343fbf2b477 "height=" 307 "width=" 521 "/>

Abstract processor (Handler) role: Defines an interface for processing requests. If necessary, the interface can define a method to set and return a reference to the home. This role is typically implemented by a Java abstract class or Java interface. The aggregation relationship of the handler class gives a reference to the sub-class, and the abstract Method HandleRequest () regulates the operation of the sub-class processing request.

Specific processor (Concretehandler) role: When a specific processor receives a request, it can choose to dispose of the request or pass the request to the other person. As the specific processor holds references to the homes, the specific processor can access the homes if necessary.
Pros: Enables the separation of requester and processor code

Cons: Understanding the processing process is difficult

3.2 Use in AOP

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M00/82/63/wKiom1dTs-agdTY7AABepZy779A983.png "title=" 4.png " alt= "Wkiom1dts-agdty7aabepzy779a983.png"/>

In fact, this is not a chain of responsibility model, it makes sense. Because these handler roles are not related to each other, the order between them is managed by the list and does not conform to the handler "either handle or forward" feature. However, from the user's point of view, this is really a responsibility chain model.

4. The use of adapter mode in AOP

4.1 Adapter Mode Structure

Object adapter:

650) this.width=650; "src=" Http://design-patterns.readthedocs.io/zh_CN/latest/_images/Adapter.jpg "alt=" Adapter.jpg "height=" 313 "width=" 724 "/>

Class Adapter

650) this.width=650; "src=" Http://design-patterns.readthedocs.io/zh_CN/latest/_images/Adapter_classModel.jpg "alt = "Adapter_classmodel.jpg" height= "344" width= "663"/>

The adapter pattern contains the following roles:

    • Target: Object abstract class

    • Adapter: Adapter Class

    • Adaptee: Adapter Class

    • Client: Customer Class


Adapter Mode Benefits
decouple the target class from the adapter class by introducing an adapter class to reuse the existing adapter class without modifying the original code.
It increases the transparency and reusability of the class, encapsulates the specific implementation in the adapter class, is transparent to the client class, and improves the reusability of the adapter.
Flexibility and scalability are very good, by using the configuration file, you can easily replace the adapter , you can not modify the original code based on the addition of new adapter classes, fully comply with the "open and close principle."

The class adapter pattern also has the following advantages:
Because the adapter class is a subclass of the adaptive class, it is possible to displace some of the adapters ' methods in the adapter class, making the adapter more flexible.
The object adapter pattern also has the following advantages:
An object adapter can adapt multiple different adapters to the same target, that is, the same adapter can match the matching class and its subclasses to the target interface.

4.2 Use of the adapter mode in spring

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M00/82/63/wKiom1dTvJTgKzu5AABi2G7apbw010.png "title=" 1111. PNG "alt=" Wkiom1dtvjtgkzu5aabi2g7apbw010.png "/>

There is another pattern in this picture. Just pay attention to methodbeforeadviceadapter->methodbeforeadviceinterceptor-->methodbeforeadvice.

5. The use of bridging mode in AOP

5.1 Pattern structure

650) this.width=650; "src=" http://design-patterns.readthedocs.io/zh_CN/latest/_images/Bridge.jpg "alt=" bridge.jpg "Height=" 393 "width=" 867 "/>

The bridging mode contains the following roles:

    • Abstraction: Abstract class

    • Refinedabstraction: Extending abstract classes

    • Implementor: Implementing Class Interfaces

    • Concreteimplementor: Concrete Implementation Class

Advantages of Bridging Mode:

Detach the abstract interface and its implementation part.
Bridging mode is sometimes similar to multiple inheritance schemes, but multiple inheritance schemes violate the single principle of responsibility of a class (that is, a class has only one reason for change), reusability is poor, and the number of classes in multiple inheritance structures is very large, bridging mode is a better solution than multiple inheritance schemes.
Bridging mode improves the scalability of the system, and it does not need to modify the original system to extend the dimension in two changing dimensions.
The implementation details are transparent to the customer, and the implementation details can be hidden from the user.
5.2 Bridging mode usage in spring

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M01/82/63/wKiom1dTyHqgqRVLAABFkG--KZ0173.png "title=" 11222. PNG "alt=" Wkiom1dtyhqgqrvlaabfkg--kz0173.png "/>

Strictly speaking, there is a refinedabstraction, this design diagram of the basic each advisor has a corresponding pointcut, and bridge the design of the mold is very different. Or that sentence, from the user's point of view, this should also be an example of bridging mode.


In short, in fact, the model of the application of the ground and theoretically, more or less will exist. In the process of continuous in-depth understanding, slowly add it.


Reference:

Http://www.tuicool.com/articles/BRZb2u

Http://design-patterns.readthedocs.io/zh_CN/latest/behavioral_patterns/strategy.html

This article is from a "simple" blog, so be sure to keep this source http://dba10g.blog.51cto.com/764602/1786250

Dead Knock Spring AOP Series 5: The use of design patterns in AOP

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.