What is AOP (aspect-oriented programming)?
AOP allows developers to dynamically modify the static Oo model and construct a system that is constantly growing to meet the new requirements, just as the real-world objects change themselves throughout their life cycles, and applications can have new capabilities in development.
AOP uses a technique called crosscutting , which splits the inside of the encapsulated object and encapsulates the behavior that affects multiple classes into a reusable module, named "Aspect", which is the facet. The so-called "aspects ", simply put, are those that are irrelevant to the business,
However, the logic or responsibility that the business module calls together, such as transaction processing, log management, permission control, etc., is packaged to reduce the duplication code of the system, reduce the coupling between the modules, and benefit the operability and maintainability of the future.
The nature of AOP technology
AOP (aspect-oriented programming, aspect-oriented programming) can be said to complement and improve OOP (object-oriented programing, object-oriented programming). OOP introduces concepts such as encapsulation, inheritance, and polymorphism to establish an object hierarchy,
A collection used to simulate public behavior. When we need to introduce public behavior to scattered objects, oop seems powerless. In other words, OOP allows you to define relationships from top to bottom, but it is not appropriate to define left-to-right relationships. such as logging capabilities.
Log code is often spread horizontally across all object hierarchies, and has nothing to do with the core functionality of the objects it spreads to. This is true for other types of code, such as security, exception handling, and transparent persistence. This irrelevant code, scattered around, is called
Crosscutting (cross-cutting) code, which in the OOP design, causes a lot of duplication of code and is not conducive to the reuse of individual modules.
AOP, on the contrary, uses a technique called "crosscutting" that splits the encapsulated object interior and encapsulates public behavior that affects multiple classes into a reusable module, called "Aspect", which is the facet. The so-called "aspect", simply put,
is to encapsulate those logic or responsibilities that are not related to the business, but are called together for business modules, to reduce duplication of code, reduce coupling between modules, and facilitate future operability and maintainability. AOP stands for a horizontal relationship,
If an "object" is a hollow cylinder that encapsulates the properties and behavior of an object, then the aspect-oriented programming approach is like a razor that cuts through the hollow cylinders to get inside the message. The cut-off aspect is the so-called "facet".
Then it hands the cut-off slices with a clever capture of the heavens, leaving no traces.
Using "crosscutting" techniques, AOP divides software systems into two parts: core concerns and crosscutting concerns. The main process of business process is the core concern, and the part that has little relation is the crosscutting concern. One feature of crosscutting concerns is that they often occur in multiple places at the core of concern,
And everywhere are basically similar. such as permission authentication, logging, transaction processing. The role of AOP is to separate the various concerns in the system, separating the core concerns from the crosscutting concerns. As Avanade's senior program architect Adam Magee said,
The core idea of AOP is "separating the business logic in the application from the generic services that support it." ”
The implementation of AOP technology, mainly divided into two categories: first, the use of dynamic Agent technology, the use of interception of messages to decorate the message to replace the original object behavior, the second is the use of static weaving, the introduction of a specific syntax to create "facet", so that the compiler can be in the compilation during the process of the
The "aspect" of the code. However, the technical characteristics of AOP are the same, namely:
1. Join point: A precise point of execution in the execution of a program, such as a method in a class. It is an abstract concept, and when implementing AOP, there is no need to define a join point.
2. Point Cut (pointcut): essentially a structure that captures the connection point. In AOP, you can define a point cut to capture calls to related methods.
3. Advice (notice): Is the execution code of point cut, is the concrete logic of executing "aspect".
4, Aspect (aspect): Point cut and advice together is aspect, which resembles a class defined in OOP, but it represents more of the horizontal relationship between objects.
5, introduce (introduced): to introduce additional methods or properties for the object, so as to achieve the purpose of modifying the object structure. Some AOP tools refer to them as mixin.
The technical features described above form the basic AOP technology, and most AOP tools implement these technologies. They can also be the basic terminology for studying AOP technology.
1.c# Manual implementation of static proxies <AOP methods to add custom before and after methods >
Suppose a scenario, when the user is logged in the system, now needs to do a version check before logging in, and user login cache processing ... < implement static Proxy with decorator mode add custom methods before and after login >
/// <summary> ///Decorator mode implements static proxy///AOP adds a custom method before and after a method/// </summary> Public classDecorator { Public Static voidShow () {User User=NewUser () {Name ="Eleven", Password ="123123123123" }; Iuserprocessor Processor=Newuserprocessor (); Processor=NewUserprocessordecorator (processor); Processor. Reguser (user); } Public InterfaceIuserprocessor {voidreguser (user user); } Public classUserprocessor:iuserprocessor { Public voidreguser (user user) {Console.WriteLine ("user login, name:{0},password:{1}", user. Name, user. Password); } } /// <summary> ///Decorator mode to provide an AOP feature/// </summary> Public classUserprocessordecorator:iuserprocessor {PrivateIuserprocessor Userprocessor {Get;Set; } Publicuserprocessordecorator (iuserprocessor userprocessor) {userprocessor=Userprocessor; } Public voidreguser (user user) {preproceed (user); This. Userprocessor.reguser (user); Postproceed (user); } Public voidpreproceed (user user) {Console.WriteLine ("Check software version information ..."); } Public voidpostproceed (user user) {Console.WriteLine ("save local cache ..."); } } }
If AOP is not used, the only way to do this is to add new version information checks and local cache processing before and after executing the method.
Public Static voidShow () {User User=NewUser () {Name ="Eleven", Password ="123123123123" }; Iuserprocessor Processor=Newuserprocessor (); Console.WriteLine ("Check software version information ..."); Processor. Reguser (user); Console.WriteLine ("Save Local Login cache ..."); }
2. Using Castle\dynamicproxy to implement dynamic proxy
using Castle.dynamicproxy;//castle.core
/// <summary> ///implementing dynamic proxies with Castle\dynamicproxy/// </summary> Public classCastleproxy { Public Static voidShow () {User User=NewUser () {Name ="Eleven", Password ="123123123123" }; Proxygenerator Generator=NewProxygenerator (); Myinterceptor Interceptor=NewMyinterceptor (); Userprocessor Userprocessor= Generator. Createclassproxy<userprocessor>(Interceptor); Userprocessor. Reguser (user); } Public classMyinterceptor:iinterceptor { Public voidIntercept (iinvocation invocation) {preproceed (invocation); Invocation. Proceed (); Postproceed (invocation); } Public voidpreproceed (iinvocation invocation) {Console.WriteLine ("Check software version information"); } Public voidpostproceed (iinvocation invocation) {Console.WriteLine ("Save Local Login Cache"); } } Public InterfaceIuserprocessor {voidreguser (user user); } Public classUserprocessor:iuserprocessor { Public Virtual voidreguser (user user) {Console.WriteLine ("User Login. Name:{0},password:{1}", user. Name, user. Password); } } }
3. Implementing dynamic proxies using. Net remoting/realproxy
/// <summary> ///implementing dynamic proxies with. Net Remoting/realproxy/// </summary> Public classProxy { Public Static voidShow () {User User=NewUser () {Name ="Eleven", Password ="123123123123" };userprocessor userprocessor= transparentproxy.create<userprocessor>(); Userprocessor. Reguser (user); } Public classMyrealproxy<t>: RealProxy {PrivateT Ttarget; PublicMyrealproxy (T target):Base(typeof(T)) { This. Ttarget =Target; } Public OverrideIMessage Invoke (IMessage msg) {Preproceede (msg); IMethodCallMessage Callmessage=(IMethodCallMessage) msg; Objectreturnvalue = CallMessage.MethodBase.Invoke ( This. Ttarget, Callmessage.args); Postproceede (msg); return NewReturnMessage (ReturnValue,New Object[0],0,NULL, Callmessage); } Public voidPreproceede (IMessage msg) {Console.WriteLine ("Check software version information"); } Public voidPostproceede (IMessage msg) {Console.WriteLine ("Save Local Login cache"); } } //TransparentProxy Public Static classTransparentProxy { Public StaticT create<t>() {T instance= activator.createinstance<t>(); Myrealproxy<T> RealProxy =NewMyrealproxy<t>(instance); T TransparentProxy=(T) realproxy.gettransparentproxy (); returnTransparentProxy; } } Public InterfaceIuserprocessor {voidreguser (user user); } Public classUserprocessor:marshalbyrefobject, Iuserprocessor { Public voidreguser (user user) {Console.WriteLine (the user logon. User name {0} password{1}", user. Name, user. Password); } } }
C # aspect-oriented Programming (AOP) leverages multiple patterns to implement dynamic proxies