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

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

问题描述

我了解面向对象的编程,并且很长时间以来一直在编写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:

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

推荐答案

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天全站免登陆