什么是面向方面的编程? [英] What is aspect-oriented programming?

查看:30
本文介绍了什么是面向方面的编程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

面向切面编程与面向对象编程>

推荐答案

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

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

然后使用 aspect-weaver 将代码编译成这样:

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;
} 

这篇关于什么是面向方面的编程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆