码迷,mamicode.com
首页 > 其他好文 > 详细

AOP 实现

时间:2014-10-20 11:36:22      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   ar   使用   strong   sp   div   on   

软件中 与业务无关的公共模块如日志系统,权限验证 等等会大量的存在于系统方法里。AOP 目的是分离这部分公共模块与业务逻辑之间的关系。

先定义业务接口:

 

  public interface IVehInfo
    {
        int GetVehicleCount();
    }

    public class Car : IVehInfo
    {

        public int GetVehicleCount()
        {
            Console.Write("Log Begian");//记录日志
            var i = 100;
            Console.Write("Log End");
            return i;
        }
    }

如何避免出现这种公共模块行为污染业务行为的方式。


1.使用代理类

    public interface IVehInfo
    {
        int GetVehicleCount();
    }

    public class Car : IVehInfo
    {

        public int GetVehicleCount()
        {
            return 100;
        }
    }



    public class CarProxy : IVehInfo
    {
        private readonly Car nCarc;
        public CarProxy(Car oCar)
        {
            this.nCarc = oCar;
        }



        public int GetVehicleCount()
        {
            Console.Write("Log Begian");//记录日志
           var ct= nCarc.GetVehicleCount();
            Console.Write("Log End");
            return ct;
        }
    }

这样做坏处是需要写大量的代理类,导致对象大爆炸。

2.使用反射发出动态构建代理类

 

AOP 实现

标签:style   blog   color   ar   使用   strong   sp   div   on   

原文地址:http://www.cnblogs.com/nessie/p/4036576.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!