What is AOP? I also want to understand AOP.

Source: Internet
Author: User

1. What is AOP?

================ The following content is from Baidu Baike =====

AOP (Aspect-Oriented Programming) can be said to be a supplement and improvement of OOP (Object-Oriented Programing, object-oriented Programming. OOP introduces concepts such as encapsulation, inheritance, and Polymorphism to establish an object hierarchy to simulate a set of public behaviors. When we need to introduce public behavior to scattered objects, OOP seems powerless. That is to say, OOP allows you to define the relationship from top to bottom, but it is not suitable for defining the relationship from left to right. For example, log function. Log Code is often horizontally distributed across all object layers, but it has nothing to do with the core functions of the objects it spreads. This is also true for other types of code, such as security, exception handling, and transparent persistence. This unrelated code distributed everywhere is called cross-cutting code. in OOP design, it leads to a large number of code duplication, which is not conducive to the reuse of each module.

The AOP technology is the opposite. It uses a technology called "cross-cutting" to segment the encapsulated object, encapsulate the public behaviors that affect multiple classes into a reusable module and name it "Aspect", that is, Aspect. The so-called "aspect" is simply to encapsulate the logic or responsibilities that are irrelevant to the business but are called by the business module to reduce repeated system code, reduce the coupling between modules and facilitate future operability and maintainability. AOP represents a horizontal relationship. If "object" is a hollow cylinder that encapsulates the attributes and behaviors of objects, then the method for Aspect-Oriented Programming is, it is like a sharp blade that splits these hollow cylinders to obtain internal messages. The cut section is the so-called "aspect. Then it restored these cut sections with the skill of winning the power of heaven without leaving any trace.

Using the "cross-cutting" technology, AOP divides the software system into two parts: the core focus and the cross-cutting focus. The main process of business processing is the core focus, and the part that has little to do with it is the cross-cutting focus. One feature of cross-cutting concerns is that they often occur in multiple places of core concerns, and are similar everywhere. For example, permission authentication, logs, and transaction processing. The function of Aop is to separate the various concerns in the system from the core concerns and the cross-cutting concerns. As Adam Magee, Avanade's senior Solution Architect, said, the core idea of AOP is to "separate the business logic in applications from the general services it supports ."

========================================================== ====================================

2. How to Implement the AOP technology?

The technology for Implementing AOP is mainly divided into two categories:

First, the dynamic proxy technology is used to describe the message by intercepting the message to replace the execution of the original object behavior;

The second is to use static weaving to introduce specific syntax to create "aspect", so that the compiler can weave "aspect" code during compilation.

However, the same way is achieved, and the technical features for Implementing AOP are the same:

1. join point: a precise execution point in program execution, such as a method in the class. It is an abstract concept. When Implementing AOP, you do not need to define a join point.
2. point cut: essentially a structure that captures the connection points. In AOP, you can define a point cut to capture calls to related methods.
3. advice (notification): indicates the Execution Code of point cut and the specific logic of executing "aspect.
4. aspect (aspect): the combination of point cut and advice is aspect. It is similar to a class defined in OOP, but it represents more of a horizontal relationship between objects.
5. introduce (Introduction): introduces additional methods or attributes to an object to modify the object structure. Some AOP tools call it mixin.

The above technical features constitute the basic AOP technology, which is implemented by most AOP tools. They can also be the basic term for studying AOP technology.

============================================= [The following content comes from the network and is edited by yourself] ========================================

3. How to Use AOP?

(1) Dynamic proxy to implement AOP:

To consider an e-commerce system, you must add or delete orders. Undoubtedly, in actual application scenarios, these actions should be combined with permission management, and only authorized users can implement these actions. The pseudocode of the traditional design method is as follows:
Public class OrderManager
{
Private ArrayList m_Orders;
Public OrderManager ()
{
M_Orders = new ArrayList ();
}
Public void AddOrder (Order order)
{
If (permissions. Verify (Permission. ADMIN ))
{

M_Orders.Add (order );
}
}

Public void RemoveOrder (Order order)
{
If (permissions. Verify (Permission. ADMIN ))
{
M_Orders.Remove (order );
}
}
}

Similarly, the E-commerce system also needs to manage commodities. It adopts the same authorization mechanism:
Public class ProductManager
{
Private ArrayList m_Products;
Public ProductManager ()
{
M_Products = new ArrayList ();
}
Public void AddProduct (Product product)
{
If (permissions. Verify (Permission. ADMIN ))
{
M_Products.Add (product );
}
}
Public void RemoveProduct (Product product)
{
If (permissions. Verify (Permission. ADMIN ))
{
M_Products.Remove (product );
}
}
}

In this way, the core business of the entire E-commerce system includes order management and commodity management, which all require the same permission management, as shown in Figure 2.4:

Figure 2.4 permission verification for e-commerce systems

 

Without a doubt, we can use AOP technology to separate the core concerns and cross-cutting concerns of the system and intercept Internal messages of Business Management Behaviors from a horizontal perspective, to achieve the purpose of organizing the permission management logic. When AddOrder () and other methods are executed, the system will verify the user's permissions and call the cross-concern logic. Therefore, this method is the join point of AOP. For e-commerce systems, each method that requires permission verification is a separate join point. Because permission verification is performed before each method is executed, you only need to define a point cut for this series of join points. When the system executes a join point, it searches for the corresponding point cut according to the definition, and then executes the logic to be implemented by this cross-cutting concern, that is, advice. Point cut and advice combine into a permission management aspect.


Figure 2.5 technical implementation of dynamic AOP cross-cutting

Since aspect is an encapsulated object, we can define such an aspect:
Private static aspect AuthorizationAspect {......}

Then define the point cut in this aspect. In the point cut, define the method to intercept the context message, for example:
Private pointcut authorizationExecution ():
Execution (public void OrderManager. AddOrder (Order) |
Execution (public void OrderManager. DeleteOrder (Order) |
Execution (public void ProductManager. AddProduct (Product) |
Execution (public void ProductManager. DeleteProduct (Product ));

Because the permission verification is completed before the order management method is executed, in before advice, define the permission check:
Before (): authorizationExecution ()
{
If! (Permissions. Verify (Permission. ADMIN ))
{
Throw new UnauthorizedException ();
}
}

By defining such a complete aspect, when the system calls the relevant methods of OrderManager or ProductManager, it triggers the point cut and then calls the corresponding advice logic. Since then, the OrderManager and ProductManager modules have completely removed the dependency between them and the permission management module. In addition, they have eliminated repeated code that is inevitable in the traditional design. This is very beneficial for building a loosely coupled, scalable system software.

(2) Static weaving to implement AOP:

The difference between static and dynamic cross-cutting is that it does not modify the execution behavior of a given object. Instead, it allows you to introduce additional method fields and attributes to modify the object structure. In addition, you can append the extension and implementation to the basic structure of the object. In AOP implementation, static cross-cutting is usually called introduce or mixin.

In the AOP technology, static cross-cutting is rarely concerned. In fact, the potential of this technology is enormous. With static cross-cutting, architects and designers can use a real object-oriented method to effectively build complex system models. Static cross-cutting allows you to insert common behaviors across the entire system in a more elegant and realistic way without creating a deep hierarchy. Especially when developing application systems, if you need to introduce third-party products and API libraries without modifying the original code, the static cross-cutting technology will play a huge role.

For example, a Mail sending and receiving system has been implemented, and Mail-like functions have been completed. However, after the product is delivered, it is found that the system has a defect. When sending and receiving emails, the email address verification function has not been implemented. Currently, third-party products provide the IValidatable interface for verification:
Public interface IValidatable
{
Bool ValidateAddress ();
}

We can use the Adapter mode in the design mode to call APIs of third-party products. We can define a new MailAdapter class that implements the IValidatable interface and inherits the Mail class:
Public class MailAdapter: Mail, IValidatable
{
Public bool ValidateAddress ()
{
If (this. getToAddress ()! = Null)
{
Return true;
}
Else
{
Return false;
}
}
}

By introducing the MailAdapter class, all the operations completed by the original Mail object will be replaced by the MailAdapter object. However, this implementation method can solve the problem of introducing new interfaces, but similar to the following code, it cannot be compiled:
Mail mail = new Mail ();
IValidatable validate = (IValidatable) mail). ValidateAddress ();

The first line of code must be modified as follows:
Mail mail = new MailAdapter ();

The static cross-cutting technology of AOP can be used to weave the IValidatable interface into the original Mail class. This is a very vivid introduce function, and its implementation is still completed in aspect:
 

Public aspect MailValidateAspect
{
Declare parents: Mail implements IValidatable;

Public boolean Mail. validateAddress ()
{
If (this. getToAddress ()! = Null)
{
Return true;
}
Else
{
Return false;
}
}
}

The static cross-cutting method does not introduce a new class similar to MailAdapter. Instead, the new method ValidateAddress () is used for the Mail class introduce through the defined MailValidateAspect (), thus, the Mail Extension is realized. Therefore, the following code is completely feasible.
Mail mail = new Mail ();
IValidatable validate = (IValidatable) mail). ValidateAddress ();

 

 

All in all, the advantages of AOP technology greatly reduce the amount of code to be written, save time, and control development costs. At the same time, developers can focus on the core business logic of the system. In addition, it facilitates the creation of loosely coupled, reusable, and scalable large software systems.

Reference connection: http://wayfarer.cnblogs.com/articles/241012.html

Http://www.cnblogs.com/zhenyulu/zhenyulu/articles/234074.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.