What is AOP? [Reprinted]

Source: Internet
Author: User

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 ."

The technology for Implementing AOP is mainly divided into two categories: one is to use dynamic proxy technology, and use the method of intercepting messages to describe 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.

2.2.2 cross-cutting technology

"Cross-cutting" is a special term of AOP. It is a relatively simple design and programming technology with powerful power, especially when it is used to build loosely coupled, scalable enterprise systems. The cross-cutting technique allows AOP to traverse established responsibilities (such as logging and performance optimization) in a given programming model.

If no cross-cutting technology is used, what is the situation of software development? In traditional programs, because the implementation of cross-cutting behaviors is scattered, it is difficult for developers to implement or change these behaviors logically. For example, the code used for logging and the Code primarily used for other duties are intertwined. Depending on the complexity and scope of the problem to be solved, the confusion may be large or small. Changing the logging policy for an application may involve hundreds of edits-even if feasible, This is a headache.

In AOP, we call these actions with public logic entangled with the core logic of other modules "Crosscutting Concern )", it spans the typical responsibility boundaries of a given programming model.

2.2.2.1 cross-cutting concerns

A concern is a specific purpose, a region we are interested in, and a logical action we need. From a technical point of view, a typical software system includes some core points of attention and system-level concerns. For example, a credit card processing system focuses on lending/deposit processing, while the system focuses on logs, transaction integrity, authorization, security, and performance, many concerns-that is, crosscutting concerns-will appear in multiple modules. If the existing programming method is used, the cross-cutting concerns will jump across multiple modules, making it difficult for the system to design, understand, implement, and evolve. Compared with the preceding method, AOP can better isolate system concerns and provide modular cross-cutting concerns.

For example, a complex system is implemented by a combination of multiple concerns, such as business logic, performance, data storage, log and scheduling information, authorization, security, thread, and error check, there are also concerns in the development process, such as easy to understand, easy to maintain, easy to trace, and easy to expand. Figure 2.1 demonstrates a system composed of a group of concerns implemented by different modules.


Figure 2.1 implement the module as a group of concerns

By identifying system requirements and implementation, we can divide these concerns in the module into core concerns and cross-cutting concerns. For core concerns, the modules that implement these concerns are independent of each other. They fulfill the business logic required by the system, which is related to specific business needs. But for the log, security, persistence and other concerns, they are the common needs of the business logic module, these logics are distributed in the core focus. In AOP, such modules are called cross-cutting concerns. The key to applying the cross-cutting technology of AOP is to recognize the concerns.

If the entire module is compared to a cylinder, the focus recognition process can be described by the prism rule. The beam passing through the prism (as required) can be illuminated everywhere in the cylinder to obtain different colors of the beam, at last, different concerns are identified. 2.2:


Figure 2.2 attention recognition: prism rule

Among the identified concerns, Business Logic is the core concern. It calls Security, Logging, Persistence, and other cross-cutting concerns.

Public class BusinessLogic
{
Public void SomeOperation ()
{
// Verify security; Securtity considerations;
// Logs are recorded before execution; Logging concerns;

DoSomething ();

// Save the data after the logical operation; Persistence focus;
// Logs of execution end records; Logging concerns;
}
}

The purpose of AOP is to separate cross-cutting concerns such as Logging from the BusinessLogic class. The AOP technology can be used to encapsulate related cross-cutting concerns to form a separate "aspect ". This ensures the reuse of cross-cutting concerns. Because the BusinessLogic class no longer contains the logic code of the Cross-concern, to call the cross-concern, you can use the cross-concern technology to intercept messages of relevant methods in the BusinessLogic class, such as the SomeOperation () method, then these "aspect" are woven into this method. Example 2.3:


Figure 2.3 resolve a cross-cutting concern to the core concern

By using the AOP technology, the design of the entire system is changed. At the beginning of analyzing system requirements, the idea of AOP is used to separate core points of concern and cross-cutting concerns. After implementing the general logic of cross-concern such as logs, transaction management, and permission control, developers can focus on their core concerns and focus on solving their business logic. At the same time, the functions provided by these encapsulated cross-cutting concerns can be used to restore all parts of the business logic to the maximum extent, without the need for special coding by developers, it also does not affect the specific business functions because of the function of modifying the cross-concern.

To establish a loosely coupled and scalable enterprise system, AOP applies two types of cross-cutting technology: Dynamic cross-cutting and static cross-cutting.

2.2.2.2 Dynamic cross-cutting

Dynamic cross-cutting refers to the process of creating a connection point in one aspect. The connection point can be applied horizontally to existing objects during execution. Dynamic cross-cutting is usually used to help add logging or identity authentication to methods at the object level. In many application scenarios, the dynamic cross-cutting technology basically represents AOP.

The core technologies of Dynamic cross-cutting include join point, point cut, advice and aspect ). Previously, I have briefly introduced the meanings of these terms. Next, I will use a specific example to describe their significance in Dynamic cross-cutting of 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.2.2.3 static cross-cutting

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:
Import com. acme. validate. Validatable;

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 ();

2.3 advantages of AOP technology

The advantages of the AOP technology are obvious. In the object-oriented world, people have proposed various methods and design principles to ensure system reusability and scalability, in order to build a software system that is loosely coupled and easy to expand. For example, the "Design Model" proposed by GOF provides us with a design model and guidelines. The design pattern maximizes the use of object-oriented features, such as the use of inheritance, polymorphism, separation of responsibilities, inversion of dependencies, abstraction-oriented, interface-oriented, finally, a flexible, scalable, and reusable class library and component is designed, and the entire system architecture is designed. In the design process, various modes are used to reflect the behavior, exposed interfaces, relationships between objects, and forms of objects in different layers. However, in view of the particularity of object encapsulation, the tentacles of the "Design Pattern" are always in the interface and abstract, while there is nothing to do with the internal objects.

With the "cross-cutting" technology, the AOP technology can penetrate into the object, and the messages transmitted between methods are used by me. Because the core focus is completely isolated from the cross-cutting focus, we can program the "aspect" independently. It allows developers to dynamically modify the static OO model and construct a system that can continuously grow to meet new requirements, just as objects in the real world will constantly change themselves in their lifecycles, applications can also have new features in development.

When designing a software system, the application of AOP technology has the following advantages:

(1) When defining all the requirements of an application for a certain service (such as a log. By identifying the focus, the service can be better defined, code can be better written, and more functions can be achieved. This method can also handle problems that occur when the Code involves multiple functions. For example, changing a function may affect other functions, in AOP, such troubles are called "tangle )".

(2) The analysis of discrete aspects using AOP technology will help to designate an expert who is better at the job for the development team. The best candidates for this job will be able to effectively leverage their skills and experience.

(3) durability. In standard object-oriented project development, different developers usually write the same code for a service, such as logging. Then they will process logs separately in their own implementations to meet the needs of different individual objects. By creating a separate code snippet, AOP provides a simple and persistent solution to this problem. This solution emphasizes the reusability and maintainability of future functions: you do not need to rewrite the Log Code over and over again in the entire application. AOP makes it possible to write only logs (logging aspect) and can provide new functions for the entire application.

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

From: http://www.cnblogs.com/zhugenqiang/archive/2008/07/27/1252761.html

 

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 ."

The technology for Implementing AOP is mainly divided into two categories: one is to use dynamic proxy technology, and use the method of intercepting messages to describe 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.

2.2.2 cross-cutting technology

"Cross-cutting" is a special term of AOP. It is a relatively simple design and programming technology with powerful power, especially when it is used to build loosely coupled, scalable enterprise systems. The cross-cutting technique allows AOP to traverse established responsibilities (such as logging and performance optimization) in a given programming model.

If no cross-cutting technology is used, what is the situation of software development? In traditional programs, because the implementation of cross-cutting behaviors is scattered, it is difficult for developers to implement or change these behaviors logically. For example, the code used for logging and the Code primarily used for other duties are intertwined. Depending on the complexity and scope of the problem to be solved, the confusion may be large or small. Changing the logging policy for an application may involve hundreds of edits-even if feasible, This is a headache.

In AOP, we call these actions with public logic entangled with the core logic of other modules "Crosscutting Concern )", it spans the typical responsibility boundaries of a given programming model.

2.2.2.1 cross-cutting concerns

A concern is a specific purpose, a region we are interested in, and a logical action we need. From a technical point of view, a typical software system includes some core points of attention and system-level concerns. For example, a credit card processing system focuses on lending/deposit processing, while the system focuses on logs, transaction integrity, authorization, security, and performance, many concerns-that is, crosscutting concerns-will appear in multiple modules. If the existing programming method is used, the cross-cutting concerns will jump across multiple modules, making it difficult for the system to design, understand, implement, and evolve. Compared with the preceding method, AOP can better isolate system concerns and provide modular cross-cutting concerns.

For example, a complex system is implemented by a combination of multiple concerns, such as business logic, performance, data storage, log and scheduling information, authorization, security, thread, and error check, there are also concerns in the development process, such as easy to understand, easy to maintain, easy to trace, and easy to expand. Figure 2.1 demonstrates a system composed of a group of concerns implemented by different modules.


Figure 2.1 implement the module as a group of concerns

By identifying system requirements and implementation, we can divide these concerns in the module into core concerns and cross-cutting concerns. For core concerns, the modules that implement these concerns are independent of each other. They fulfill the business logic required by the system, which is related to specific business needs. But for the log, security, persistence and other concerns, they are the common needs of the business logic module, these logics are distributed in the core focus. In AOP, such modules are called cross-cutting concerns. The key to applying the cross-cutting technology of AOP is to recognize the concerns.

If the entire module is compared to a cylinder, the focus recognition process can be described by the prism rule. The beam passing through the prism (as required) can be illuminated everywhere in the cylinder to obtain different colors of the beam, at last, different concerns are identified. 2.2:


Figure 2.2 attention recognition: prism rule

Among the identified concerns, Business Logic is the core concern. It calls Security, Logging, Persistence, and other cross-cutting concerns.

Public class BusinessLogic
{
Public void SomeOperation ()
{
// Verify security; Securtity considerations;
// Logs are recorded before execution; Logging concerns;

DoSomething ();

// Save the data after the logical operation; Persistence focus;
// Logs of execution end records; Logging concerns;
}
}

The purpose of AOP is to separate cross-cutting concerns such as Logging from the BusinessLogic class. The AOP technology can be used to encapsulate related cross-cutting concerns to form a separate "aspect ". This ensures the reuse of cross-cutting concerns. Because the BusinessLogic class no longer contains the logic code of the Cross-concern, to call the cross-concern, you can use the cross-concern technology to intercept messages of relevant methods in the BusinessLogic class, such as the SomeOperation () method, then these "aspect" are woven into this method. Example 2.3:


Figure 2.3 resolve a cross-cutting concern to the core concern

By using the AOP technology, the design of the entire system is changed. At the beginning of analyzing system requirements, the idea of AOP is used to separate core points of concern and cross-cutting concerns. After implementing the general logic of cross-concern such as logs, transaction management, and permission control, developers can focus on their core concerns and focus on solving their business logic. At the same time, the functions provided by these encapsulated cross-cutting concerns can be used to restore all parts of the business logic to the maximum extent, without the need for special coding by developers, it also does not affect the specific business functions because of the function of modifying the cross-concern.

To establish a loosely coupled and scalable enterprise system, AOP applies two types of cross-cutting technology: Dynamic cross-cutting and static cross-cutting.

2.2.2.2 Dynamic cross-cutting

Dynamic cross-cutting refers to the process of creating a connection point in one aspect. The connection point can be applied horizontally to existing objects during execution. Dynamic cross-cutting is usually used to help add logging or identity authentication to methods at the object level. In many application scenarios, the dynamic cross-cutting technology basically represents AOP.

The core technologies of Dynamic cross-cutting include join point, point cut, advice and aspect ). Previously, I have briefly introduced the meanings of these terms. Next, I will use a specific example to describe their significance in Dynamic cross-cutting of 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.2.2.3 static cross-cutting

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:
Import com. acme. validate. Validatable;

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 ();

2.3 advantages of AOP technology

The advantages of the AOP technology are obvious. In the object-oriented world, people have proposed various methods and design principles to ensure system reusability and scalability, in order to build a software system that is loosely coupled and easy to expand. For example, the "Design Model" proposed by GOF provides us with a design model and guidelines. The design pattern maximizes the use of object-oriented features, such as the use of inheritance, polymorphism, separation of responsibilities, inversion of dependencies, abstraction-oriented, interface-oriented, finally, a flexible, scalable, and reusable class library and component is designed, and the entire system architecture is designed. In the design process, various modes are used to reflect the behavior, exposed interfaces, relationships between objects, and forms of objects in different layers. However, in view of the particularity of object encapsulation, the tentacles of the "Design Pattern" are always in the interface and abstract, while there is nothing to do with the internal objects.

With the "cross-cutting" technology, the AOP technology can penetrate into the object, and the messages transmitted between methods are used by me. Because the core focus is completely isolated from the cross-cutting focus, we can program the "aspect" independently. It allows developers to dynamically modify the static OO model and construct a system that can continuously grow to meet new requirements, just as objects in the real world will constantly change themselves in their lifecycles, applications can also have new features in development.

When designing a software system, the application of AOP technology has the following advantages:

(1) When defining all the requirements of an application for a certain service (such as a log. By identifying the focus, the service can be better defined, code can be better written, and more functions can be achieved. This method can also handle problems that occur when the Code involves multiple functions. For example, changing a function may affect other functions, in AOP, such troubles are called "tangle )".

(2) The analysis of discrete aspects using AOP technology will help to designate an expert who is better at the job for the development team. The best candidates for this job will be able to effectively leverage their skills and experience.

(3) durability. In standard object-oriented project development, different developers usually write the same code for a service, such as logging. Then they will process logs separately in their own implementations to meet the needs of different individual objects. By creating a separate code snippet, AOP provides a simple and persistent solution to this problem. This solution emphasizes the reusability and maintainability of future functions: you do not need to rewrite the Log Code over and over again in the entire application. AOP makes it possible to write only logs (logging aspect) and can provide new functions for the entire application.

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.