使用装饰器模式做类的增强

来源:互联网 发布:蛀牙漱口水推荐 知乎 编辑:程序博客网 时间:2024/05/21 19:32

我们已经实现了用户注册功能,现在想增加日志记录功能。具体来讲就是在用户注册前后,分别输出一条日志。我们当然可以修改原有的业务代码。

现在换个角度来问两个问题:
1. 团队开发中,我们很可能根本拿不到源代码,那又怎么去增加这个功能呢?
2. 这次需求是增加日志,以后再增加其他需求(比如异常处理),是不是仍然要改业务类呢?

总结一下:
我们要在不修改原有类业务代码的前提下,去做类的增强。我们的设计要符合面向对象的原则:对扩展开放,对修改封闭

都有哪些办法呢?我们尝试以下几种方法:

  • 使用装饰器模式做类的增强
  • 使用.Net代理模式做类的增强
  • 使用Castle做类的增强
  • 使用Unity做类的增强
  • 使用Unity做类的增强(续)
  • 使用Autofac做类的增强

原有业务类

业务模型

namespace testAopByDecorator{    public class User    {        public string Name { get; set; }        public int Id { get; set; }    }}

接口设计

namespace testAopByDecorator{    public interface IUserProcessor    {        void RegisterUser(User user);    }}

业务实现

using System;namespace testAopByDecorator{    public class UserProcessor : IUserProcessor    {        public void RegisterUser(User user)        {            if (user == null)            {                return;            }            Console.WriteLine(string.Format("注册了一个用户{0}:{1}", user.Id, user.Name));        }    }}

上层调用

using System;namespace testAopByDecorator{    class Program    {        private static User user = new User { Id = 1, Name = "滇红" };        static void Main(string[] args)        {            Register();            Console.ReadKey();        }        private static void Register()        {            IUserProcessor processor = new UserProcessor();            processor.RegisterUser(user);        }    }}

使用装饰器模式做类的增强

装饰器类

using System;namespace testAopByDecorator{    public class UserProcessorDecorator : IUserProcessor    {        private IUserProcessor _processor;        public UserProcessorDecorator(IUserProcessor processor)        {            this._processor = processor;        }        public void RegisterUser(User user)        {            if (this._processor == null)            {                return;            }            before(user);            this._processor.RegisterUser(user);            after(user);        }        private void after(User user)        {            Console.WriteLine("注册用户后:" + user.Name);        }        private void before(User user)        {            Console.WriteLine("注册用户前:" + user.Name);        }    }}

上层调用

using System;namespace testAopByDecorator{    class Program    {        private static User user = new User { Id = 1, Name = "滇红" };        static void Main(string[] args)        {            RegisterAndLog();            Console.ReadKey();        }        private static void RegisterAndLog()        {            IUserProcessor processor = new UserProcessor();            IUserProcessor decorator = new UserProcessorDecorator(processor);//装饰原有业务类            decorator.RegisterUser(user);//遵守接口契约        }    }}

对比一下扩展前后的业务展现
这里写图片描述

0 0
原创粉丝点击