/***************************************************** *CreateBy:joe zhou *CreateDate:2011-10-18 *Description:装饰器模式实现的拦截器 *****************************************************/ using System; namespace T4Mvp { /// <summary> /// 组件接口 /// </summary> public interface IComponent { /// <summary> /// 上下文对象 /// </summary> object Context { get; } /// <summary> /// 核心执行方法 /// </summary> void Execute(); } /// <summary> /// 装饰器对象 /// </summary> public abstract class Decorator : IComponent { private object _context; private IComponent _decoratee; /// <summary> /// 构造函数 /// </summary> /// <exception cref="System.ArgumentNullException">参数为空时产生参数空异常</exception> protected Decorator(IComponent decoratee) { #region 参数检查 if (decoratee == null) { throw new ArgumentNullException("decoratee"); } #endregion this._decoratee = decoratee; this._context = decoratee.Context; } #region 切点 /// <summary> /// 执行之前调用 /// </summary> protected abstract void Starting(); /// <summary> /// 执行完成后调用 /// </summary> protected abstract void Completed(); #endregion #region IComponent 成员 public object Context { get { return this._context; } } public void Execute() { Starting(); this._decoratee.Execute(); Completed(); } #endregion } }
关于为什么要用AOP?很多人总是说记日志,个人以为仅仅为了记日志使用AOP有点搞笑。我认为AOP的魅力在于我们有一个开发好的功能,后来发现功能不完善,需要做一些处理而又不愿意去修改原有的封装,这个时候AOP就粉墨登场了!