享受代码,享受人生

SOA is an integration solution. SOA is message oriented first.
The Key character of SOA is loosely coupled. SOA is enriched
by creating composite apps.
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

No Buzzword AOP --- with AOP(Method interceptor)

Posted on 2005-10-10 17:23  idior  阅读(2187)  评论(7编辑  收藏  举报

上文中, 已经将Print功能抽象成一个类, 从而达到减少重复代码的目的.
但是你肯定会在某些方面觉得不太舒服

   15         public double Speed

   16         {

   17             get

   18             {

   19                 return speed;

   20             }

   21             set

   22             {

   23                 propPrinter.Print(false,speed);

   24                 speed = value;

   25                 propPrinter.Print(true,speed);

   26             }

   27         }

虽然Print功能的定义集中到了一个类中, 但是调用Print功能的代码还是散布在各个地方.
减少重复的最高境界就是实现一个需求只有一处实现.

但是现在我们并没有做到这点, 我们仅仅实现了一个需求只有一处定义,但是有n处调用.
仔细思考一下面向对象能够解决这个问题吗?

为什么我们需要函数(结构化编程)?  --- 为了消除重复               需求:定义:调用=1:M:N (M<N) 
为什么我们需要类(面向对象)? --- 为了消除重复                     需求:定义:调用=1:1:N
为什么我们需要方面(面向方面)? --- 为了消除重复                   需求:定义:调用=1:1:1

AOP如何达到只有一处调用的呢? 面向对象并没有提供一个让我们定义调用的地方, 而AOP提供了这么一个地方---Aspect.

先来看看Aspect#中有关Aspect的定义:
aspect PropertyAspect for Employer
     pointcut propertywrite(*)
           advice(PrinterInterceptor)
     end
end

Aspect文件的说明:
    其中我们可以看到for后面定义需要调用功能的那些类,这里为了简单起见我只定义了一个. 
    再来看pointcut.
这里定义了类中的那些地方需要调用功能.这里我定义了类中的所有"写属性".也就是说当修改属性的时候就会调用到之前定义的功能. 
    那么调用什么功能,怎么调用就是在advice后面定义的PrinterInterceptor描述的. 

    9     public class PrinterInterceptor :IMethodInterceptor

   10     {

   11         public object Invoke(IMethodInvocation invocation)

   12         {

   13             PropertyPrinter printer=new PropertyPrinter();

   14             string propName=invocation.Method.Name.Substring(4);

   15 

   16             object originalValue=invocation.Method.DeclaringType.GetProperty(propName).GetValue(invocation.This,null);

   17             printer.Print(false,originalValue);

   18 

   19             object returnVal = invocation.Proceed();

   20 

   21             object modifiedValue=invocation.Method.DeclaringType.GetProperty(propName).GetValue(invocation.This,null);

   22             printer.Print(true,modifiedValue);

   23 

   24             return returnVal;

   25         }

   26     }

通过这些概念的定义我们就可以实现对功能调用的一次定义, 而不再象以前那样要手工的在各个类各个属性中调用我们的Print方法.

AOP 实现了 需求 :  实现 = 1 :  1 ,  最大程度地减少了重复. 现在你还要问什么是AOP了吗? AOP是不是可以被用在很多地方呢?


注: 本文是AOP入门文章, 所有表述都是基于简单考虑.

示例下载
AOP Practice with AspectWeaver0.6 - DebugPropertyValueModifying   Teddy's Static IL Weaveing way