标签:private [] 访问者模式 模式 asp.net run null nbsp bsp
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. 动态代理
标签:private [] 访问者模式 模式 asp.net run null nbsp bsp
原文地址:http://www.cnblogs.com/wj033/p/6139644.html