首页 > 代码库 > 几种Aop实现
几种Aop实现
1. 通过继承实现
public interface IA{ void DoSth();}public class A: IA{ public virtual void DoSth() { }}public class B : A,IA{ public override void DoSth() { before(); base.DoSth(); after(); } public void before() { } public void after() { }}
2. 装饰者/代理模式(由继承改作组合)
public interface IA{ void DoSth();}public class A2: IA{ public void DoSth() { }}public class B2 : IA{ private IA a; public B2(IA a) { this.a = a; } public void DoSth() { before(); this.a.DoSth(); after(); } public void before() { } public void after() { }}
3. 访问者模式
public interface IA{ void DoSth();}public class A3 : IA{ public void DoSth() { } public void Proceed() { DoSth(); }}public class MyInterceptor{ public void Intercept(IA invocation) { before(); if(invocation != null) invocation.DoSth(); after(); } public void before() { } public void after() { }}
4.ASP.NET MVC中的拦截器。
public interface IAdditionalOp{ void before(); void after();}public class AdditionalOp :Attribute, IAdditionalOp{ public void before() { } public void after() { }}public class A4{ [AdditionalOp] public void DoSth() { }}public class B4{ public void Run() { var classUnder = typeof(A4); var allMethods = classUnder.GetMethods(); var methodUnder = allMethods.Where(m => m.Name == "DoSth"); foreach (MethodInfo methodInfo in methodUnder) { Attribute[] attributes = Attribute.GetCustomAttributes(methodInfo, typeof(AdditionalOp)); foreach (var item in attributes) { (item as AdditionalOp).before(); } A4 a4 = new A4(); a4.DoSth(); foreach (var item in attributes) { (item as AdditionalOp).after(); } } }}
5. 动态代理
.NET:动态代理的 “5 + 1” 模式
几种Aop实现
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。