什么是面向方面编程?

发布于 2024-07-08 04:04:32 字数 251 浏览 11 评论 0原文

我了解面向对象编程,并且已经编写OO程序很长时间了。 人们似乎在谈论面向方面的编程,但我从未真正了解它是什么或如何使用它。 基本范式是什么?

这个问题是相关的,但并没有完全提出:

面向方面编程与. 面向对象编程

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

酒中人 2024-07-15 04:04:32

AOP 解决了横切关注点的问题,横切关注点可以是在不同方法中重复的任何类型的代码,并且通常不能完全重构到自己的模块中,例如日志记录或验证。 因此,使用 AOP,您可以将这些内容从主代码中删除,并像这样垂直定义它:

function mainProgram()
{ 
   var x =  foo();
   doSomethingWith(x);
   return x;
}

aspect logging
{ 
    before (mainProgram is called):
    { 
       log.Write("entering mainProgram");
    }

    after (mainProgram is called):
    { 
       log.Write(  "exiting mainProgram with return value of "
                  + mainProgram.returnValue);
    }
 } 

aspect verification
{ 
    before (doSomethingWith is called):
    { 
       if (doSomethingWith.arguments[0] == null) 
       { 
          throw NullArgumentException();
       }

       if (!doSomethingWith.caller.isAuthenticated)
       { 
          throw Securityexception();
       }
    }
 }

然后使用切面编织器将代码编译为:

function mainProgram()
{ 
   log.Write("entering mainProgram");

   var x = foo();   

   if (x == null) throw NullArgumentException();
   if (!mainProgramIsAuthenticated()) throw Securityexception();
   doSomethingWith(x);   

   log.Write("exiting mainProgram with return value of "+ x);
   return x;
} 

AOP addresses the problem of cross-cutting concerns, which would be any kind of code that is repeated in different methods and can't normally be completely refactored into its own module, like with logging or verification. So, with AOP you can leave that stuff out of the main code and define it vertically like so:

function mainProgram()
{ 
   var x =  foo();
   doSomethingWith(x);
   return x;
}

aspect logging
{ 
    before (mainProgram is called):
    { 
       log.Write("entering mainProgram");
    }

    after (mainProgram is called):
    { 
       log.Write(  "exiting mainProgram with return value of "
                  + mainProgram.returnValue);
    }
 } 

aspect verification
{ 
    before (doSomethingWith is called):
    { 
       if (doSomethingWith.arguments[0] == null) 
       { 
          throw NullArgumentException();
       }

       if (!doSomethingWith.caller.isAuthenticated)
       { 
          throw Securityexception();
       }
    }
 }

And then an aspect-weaver is used to compile the code into this:

function mainProgram()
{ 
   log.Write("entering mainProgram");

   var x = foo();   

   if (x == null) throw NullArgumentException();
   if (!mainProgramIsAuthenticated()) throw Securityexception();
   doSomethingWith(x);   

   log.Write("exiting mainProgram with return value of "+ x);
   return x;
} 
戏剧牡丹亭 2024-07-15 04:04:32

不幸的是,要让 AOP 在正常的中大型组织中真正发挥作用似乎出人意料地困难。 (编辑器支持、控制感、从导致代码腐烂的不那么重要的事情开始的事实、人们回家与家人团聚等)

我把希望寄托在面向组合的编程

在这里查看即将推出的实现:qi4j.org/

PS。 实际上,我认为 AOP 的优点之一也是它的致命弱点:它是非侵入性的,让人们尽可能忽略它,因此在大多数组织中它将被视为次要问题。

Unfortunately, it seems to be surprisingly difficult to make AOP really useful in a normal mid-large size organization. (Editor support, sense of control, the fact that you start with the not-so-important things leading to code-rot, people going home to their families, etc.)

I put my hopes to composite oriented programming, which is something more and more realistic. It connects to many popular ideas and gives you something really cool.

Look at an up and coming implementation here: qi4j.org/

PS. Actually, I think that one of the beauties with AOP is also its achilles heel: Its non-intrusive, letting people ignore it if they can, so it will be treated as a secondary concern in most organizations.

坏尐絯℡ 2024-07-15 04:04:32

复制自 Spring in Action

AOP 通常被定义为一种促进分离的技术
软件系统中的问题。 系统由几个组成
组件,每个组件负责一项特定的功能。
但这些组件通常还承担额外的职责
超出其核心功能。 系统服务,例如日志记录、
事务管理和安全性经常会出现在
其核心职责是其他的组件。 这些系统
服务通常被称为横切关注点,因为
它们倾向于跨越系统中的多个组件。

Copied from Spring in Action

AOP is often defined as a technique that promotes separation of
concerns in a software system. Systems are composed of several
components, each responsible for a specific piece of functionality.
But often these components also carry additional responsibilities
beyond their core functionality. System services such as logging,
transaction management, and security often find their way into
components whose core responsibilities is something else. These system
services are commonly referred to as cross-cutting concerns because
they tend to cut across multiple components in a system.

陪你到最终 2024-07-15 04:04:32

为了完整性而从副本中复制(爱因斯坦):

经典的例子是安全和日志记录。 不是在应用程序中编写代码来记录 x 的出现或检查对象 z 的安全访问控制,而是使用正常代码的“带外”语言装置,它可以系统地注入安全性或登录到本来没有它们的例程中这样即使你的代码不提供它——它也会被处理。

一个更具体的例子是操作系统提供对文件的访问控制。 软件程序不需要检查访问限制,因为底层系统会为其完成这项工作。

根据我的经验,如果您认为需要 AOP,那么您实际上确实需要投入更多的时间和精力来进行系统内适当的元数据管理,并重点关注深思熟虑的结构/系统设计。

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.

丶视觉 2024-07-15 04:04:32

为了完整性而从副本中复制(Buzzer):.

NET 中的类和方法属性是面向方面编程的一种形式。 您用属性来装饰您的类/方法。 这会在幕后向您的类/方法添加代码,以执行属性的特定功能。 例如,将类标记为可序列化可以使其自动序列化以存储或传输到另一个系统。 其他属性可能会将某些属性标记为不可序列化,并且这些属性将自动从序列化对象中省略。 序列化是一个方面,由系统中的其他代码实现,并通过应用“配置”属性(装饰)应用于您的类。

Copied from a duplicate for completeness (Buzzer):

Class and method attributes in .NET are a form of aspect-oriented programming. You decorate your classes/methods with attributes. Behind the scenes this adds code to your class/method that performs the particular functions of the attribute. For example, marking a class serializable allows it to be serialized automatically for storage or transmission to another system. Other attributes might mark certain properties as non-serializable and these would be automatically omitted from the serialized object. Serialization is an aspect, implemented by other code in the system, and applied to your class by the application of a "configuration" attribute (decoration) .

清醇 2024-07-15 04:04:32

有一个AOP的例子,它以spring AOP为例。 这个例子很容易理解。

Spring AOP(面向切面编程)框架用于模块化切面中的横切关注点。 简单来说,它只是一个拦截器,用来拦截一些流程,比如当一个方法被执行时,Spring AOP可以劫持正在执行的方法,并在方法执行之前或之后添加额外的功能。

参考:http://www.mkyong.com/spring/spring-aop-示例-建议/

There is an example of AOP, it used spring AOP as an example. The example is quite easy to understand.

Spring AOP (Aspect-oriented programming) framework is used to modularize cross-cutting concerns in aspects. Put it simple, it’s just an interceptor to intercept some processes, for example, when a method is execute, Spring AOP can hijack the executing method, and add extra functionality before or after the method execution.

Reference: http://www.mkyong.com/spring/spring-aop-examples-advice/

泪冰清 2024-07-15 04:04:32

AOP 是一种更好地模块化应用程序以实现跨越多个边界的功能的方法。 AOP 是封装这些功能的另一种方法,并通过将这些横切关注点(日志记录、错误处理等)从应用程序的主要组件中移出来遵循单一职责。 如果使用得当,AOP 可以随着时间的推移提高应用程序的可维护性和可扩展性。

AOP is a way to better modularize your application for functionality that spans across multiple boundaries. AOP is another way to encapsulate these features and follow Single Responsiblity by moving these cross-cutting concerns (logging, error handling, etc.) out of the main components of your application. When used appropriately AOP can lead to higher levels of maintainability and extensibility in your application over time.

划一舟意中人 2024-07-15 04:04:32

我们面向方面编程的目标是减少样板代码的数量。

举个例子,我们有一个服务,在这个服务中,我们首先打印service.start()日志,然后打印服务事务日志,最后打印标准日志。

我们的1.log流程和3.log流程在包下是一样的,所以用它作为Cross Cutting可以减少boirplate代码的编写。

什么是面向方面编程?

AOP 是一种有助于降低软件复杂性并提高模块化的方法。 这里模块化的目的是将非功能性代码,即应用程序过程中系统许多部分使用的交叉利益,分离成小块(交叉关注点分离)。通过这种方式,将在整个应用程序中使用的结构从系统中抽象出来并进行封装。 它允许它在很多地方使用。 总的来说,可以说AOP有助于使现有系统变得更好而不是解决问题。

此时,我们就可以在这里进行常见的运算和归约运算了。

AOP 的好处是什么?

  • 我们的应用程序更加灵活且易于管理,
  • 摆脱重复的代码模式,
  • 更干净、更易理解的代码,
  • 与核心逻辑和交叉点分离。

Our goal in Aspect Oriented Programming is to reduce the amount of boilerplate code.

Let's give an example, we have a service, and in this service, let's first print the service.start() log, then the service transaction log, and finally the standard log.

Our 1.log process and 3.log process are the same under the package, so we can reduce boirplate code writing by using it as Cross Cutting.

What is Aspect Oriented Programming?

AOP is an approach that helps reduce the complexity of the software and increase modularity. The purpose of modularization here is to separate the non-functional code, that is, the intersecting interests, used in many parts of the system during the application, into small pieces (Separation of Cross Cutting Concerns).In this way, the structures that will be used throughout the application are abstracted from the system and encapsulated. It allows it to be used in many places. In general, it can be said that AOP helps to make the existing system better rather than solving a problem.

At this point, we can perform common operations and reduction operations here.

What are the benefits of AOP?

  • Our application is more flexible and easy to manage,
  • Getting rid of repetitive code patterns,
  • A cleaner and more understandable code,
  • Separation from core logic and intersections.
踏雪无痕 2024-07-15 04:04:32

类比:想象一下你正在建造一个又大又复杂的房子。 在像 OOPS 这样的编程范式中,我们有不同的房间(类),每个房间都有不同的功能(方法)和东西(数据)。 现在我们发现我们家存在安全隐患。 因此,我们制定了一个总体规划,即在我们家的每个房间安装闭路电视摄像机。
在OOPS中,我们去了每个房间,并在房间的入口处安装了闭路电视摄像机。 这就像为每个房间一遍又一遍地执行相同的任务。
但在 AOP 中,我们不需要一遍又一遍地执行相同的任务。 相反,它允许我们创建一个安装闭路电视的计划(称为方面),并且该计划可以立即编织到所有房间。 我们只需要专注于主要设计,AOP 就会在我们需要的地方添加安全摄像头。

因此,AOP 的关键术语是:

  1. 关注点(或横切关注点)

    • 这些功能必须添加到程序的多个部分。
    • 示例:安全性、日志记录或错误处理
    • 在我们的类比中,我们担心的是安全风险
  2. 方面

    • 这就像处理问题的总体计划。 它将横切关注点封装在一个模块化单元中。
    • 在我们的类比中,我们计划在每个房间安装闭路电视是各个方面
  3. 连接点

    • 这是我们程序中要应用代码的特定点
    • 在我们的类比中,我们在房间的入口处安装了闭路电视
  4. 建议

    • Advice 是实现我们的横切关注点的实际代码,它在连接点中定义

您可以轻松理解它的另一个示例

假设我们必须将“Hello Worlds”打印到控制台。 现在我们想在每次打印此消息时进行记录。 在 OOP 等传统方法中,我们会转到打印语句并添加日志行(如 Console.log("message))。但是在 AOP 中,我们创建一个方面,表示“每次有打印语句时,也记录它”我们不触及原始的打印语句;我们只是应用我们的方面,瞧!在不更改核心代码的情况下添加日志记录

优点:

  • 我们可以保持代码整洁,并且关注点被整齐地分开
  • 改变一个关注点不会影响整个程序
  • 。可以在程序的不同部分

重用 缺点:

  • 学习困难
  • 调试复杂

Analogy: Imagine you are building a big and complicated home. In programming paradigm like OOPS, we have different rooms(classes) each with different functionalities(methods) and stuff(data). Now we found out we have security risk in our home. So we create a master plan ie to install CCTV camera to every room of our home.
In OOPS, we go to each room, and install CCTV camera in the entrance of the room. Its like doing same task over and over again for every room.
But in AOPs, we dont need to do same task over and over again. Instead it allow us to create a plan(called aspects) for installing CCTV and the plan can be weaved in all the room at once. We just need to focus on main design and AOP takes care of adding security cameras wherever we need.

So the key terminologies of AOP are:

  1. Concerns (or cross cutting concerns)

    • These are functionalities that has to be added across multiple parts of program.
    • Example: Security, logging or error handling
    • In our analogy, our concern is the security risk
  2. Aspects

    • It is like master plan for dealing with concern. It encapsulate cross cutting concerns in a modular unit.
    • In our analogy, our plan to install CCTV in every room is aspects
  3. Join points

    • It is the specific points on our program where we want to apply the code
    • In our analogy , we were installing cctv in the room's entrance
  4. Advice

    • Advice is the actual code that implements our cross cutting concern and it is defined in join points

Another example from which you can understand it easily

Let's say we have to print 'Hello Worlds' to the console. Now we want to log every time this message is printed. In traditional methods like OOPs, we'd go to print statement and add log line (like Console.log("message)). But in AOP, we create an aspect that says "Every time there is print statement, also log it" . We don't touch the original print statement; we just apply our aspect and voila ! Logging is added without changing core code.

Merits:

  • We can keep our code clean and concerns are neatly separated
  • Changing one concern doesn't affect whole program
  • Aspect can be reused in different parts of the programs

Demerits:

  • Hard to learn
  • Complex to debug
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文