面向切面编程(AOP)

汪星人 2018-10-09 01:45143 阅读

结合设计模式,通过代码理解面向切面编程,有代码的很好理解的,5分钟可以看三遍

通过,结构型设计模式,装饰器模式来实现AOP,代码如下

 /// <summary>
    /// 装饰器模式实现静态代理
    /// AOP 在方法前后增加自定义的方法
    /// </summary>
    public class DecoratorAOP
    {
        public static void Show()
        {
            User user = new User()
            {
                Name = "Eleven",
                Password = "123123123123"
            };
            //直接调用
            IUserProcessor processor = new UserProcessor();
            processor.RegUser(user);
            Console.WriteLine("***************");
            //通过装饰器模式,在方法执行前后添加功能
            processor = new UserProcessorDecorator(processor);
            processor.RegUser(user);
        }

        public interface IUserProcessor
        {
            void RegUser(User user);
        }
        public class UserProcessor : IUserProcessor
        {
            public void RegUser(User user)
            {
                Console.WriteLine("用户已注册。Name:{0},PassWord:{1}", user.Name, user.Password);
            }
        }

        /// <summary>
        /// 装饰器的模式去提供一个AOP功能
        /// </summary>
        public class UserProcessorDecorator : IUserProcessor
        {
            private IUserProcessor _UserProcessor { get; set; }
            public UserProcessorDecorator(IUserProcessor userprocessor)
            {
                this._UserProcessor = userprocessor;
            }

            public void RegUser(User user)
            {
                BeforeProceed(user);

                this._UserProcessor.RegUser(user);

                AfterProceed(user);
            }

            /// <summary>
            /// 业务逻辑之前
            /// </summary>
            /// <param name="user"></param>
            private void BeforeProceed(User user)
            {
                Console.WriteLine("方法执行前");
            }
            /// <summary>
            /// 业务逻辑之后
            /// </summary>
            /// <param name="user"></param>
            private void AfterProceed(User user)
            {
                Console.WriteLine("方法执行后");
            }
        }

    }

 

通过,结构型设计模式,代理模式来实现AOP,代码如下

   /// <summary>
    /// 代理模式实现静态代理
    /// AOP 在方法前后增加自定义的方法
    /// </summary>
    public class ProxyAOP
    {
        public static void Show()
        {
            User user = new User()
            {
                Name = "Eleven",
                Password = "123123123123"
            };
            IUserProcessor processor = new UserProcessor();
            //直接调用方法
            processor.RegUser(user);
            Console.WriteLine("***************");
            //实现AOP,在执行前后加其他方法
            processor = new ProxyUserProcessor();
            processor.RegUser(user);
        }

        public interface IUserProcessor
        {
            void RegUser(User user);
        }
        public class UserProcessor : IUserProcessor
        {
            public void RegUser(User user)
            {
                Console.WriteLine("用户已注册。Name:{0},PassWord:{1}", user.Name, user.Password);
            }
        }

        /// <summary>
        /// 代理模式去提供一个AOP功能
        /// </summary>
        public class ProxyUserProcessor : IUserProcessor
        {
            private IUserProcessor _UserProcessor = new UserProcessor();

            public void RegUser(User user)
            {
                BeforeProceed(user);
                this._UserProcessor.RegUser(user);
                AfterProceed(user);
            }

            /// <summary>
            /// 业务逻辑之前
            /// </summary>
            /// <param name="user"></param>
            private void BeforeProceed(User user)
            {
                Console.WriteLine("方法执行前");
            }
            /// <summary>
            /// 业务逻辑之后
            /// </summary>
            /// <param name="user"></param>
            private void AfterProceed(User user)
            {
                Console.WriteLine("方法执行后");
            }
        }

    }

 

 

通过Unity实现AOP,配置太复杂就不贴了。。。就一个实现类的代码,可以用于添加方法的日志,异常处理,不用修改方法本身,不用挨个方法+Log.Info()了,通过Unity(IOC)创建的对象都能用,代码如下

 public class LogBeforeBehavior : IInterceptionBehavior
    {
        public IEnumerable<Type> GetRequiredInterfaces()
        {
            return Type.EmptyTypes;
        }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            Console.WriteLine("LogBeforeBehavior");
            Console.WriteLine(input.MethodBase.Name);
            foreach (var item in input.Inputs)
            {
                Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item));
                //反射&序列化获取更多信息
            }
            return getNext().Invoke(input, getNext);//
        }

        public bool WillExecute
        {
            get { return true; }
        }
    }

 再加一个Unity创建对象和调用的代码吧,NuGet添加Unity的引用

public class UnityConfigAOP
    {
        public static void Show()
        {
            User user = new User()
            {
                Name = "Eleven",
                Password = "12345678934534643"
            };
             //这个是代码块,好神奇的呦
            {
                //配置UnityContainer
                IUnityContainer container = new UnityContainer();
                ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
                fileMap.ExeConfigFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "CfgFiles\\Unity.Config");
                Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
                UnityConfigurationSection configSection = (UnityConfigurationSection)configuration.GetSection(UnityConfigurationSection.SectionName);
                configSection.Configure(container, "aopContainer");

                IUserProcessor processor = container.Resolve<IUserProcessor>();
                processor.RegUser(user);

            }
        }
    }    

 

 

 

回复数量: 0
暂无评论~~
  请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!