What is aspect-oriented programming?

2019-01-03 19:55发布

I understand object oriented programming, and have been writing OO programs for a long time. People seem to talk about aspect-oriented programming, but I've never really learned what it is or how to use it. What is the basic paradigm?

This question is related, but doesn't quite ask it:

Aspect-Oriented Programming vs. Object Oriented Programming

标签: aop paradigms
8条回答
Anthone
2楼-- · 2019-01-03 20:25

Copied from a duplicate for completeness (Einstein):

The classic examples are security and logging. Instead of writing code within your application to log occurance of x or check object z for security access control there is a language contraption "out of band" of normal code which can systematically inject security or logging into routines that don't nativly have them in such a way that even though your code doesn't supply it -- its taken care of.

A more concrete example is the operating system providing access controls to a file. A software program does not need to check for access restrictions because the underlying system does that work for it.

If you think you need AOP in my experience you actually really need to be investing more time and effort into appropriate meta-data management within your system with a focus on well thought structural / systems design.

查看更多
爷的心禁止访问
3楼-- · 2019-01-03 20:27

AOP can be used to perform actions that are not related to the business logic of your app such as logging, caching, etc. These actions can be put in a separate part of your app and then reused throughout the application. There are usually two ways of accomplishing this. Injecting code automagically by a preprocessor before/after a method, or attaching proxy classes that intercept a method call and can then execute things before/after a method call.

Here is an example in .Net. It uses proxy classes to intercept method calls and execute code before of after saif method calls.

Aspect Oriented Programming (AOP) in .NET Core and C# using AutoFac and DynamicProxy

查看更多
登录 后发表回答