您的位置:首页 > 编程语言 > C#

C#模拟拦截器的实现

2013-03-15 13:08 239 查看
在SSH项目开发的过程中,Struts中大部分的功能是通过拦截器实现的。从编程思想上讲,拦截器也是AOP的实现。这里通过C#代码来模拟一个简单的拦截器。

首先来看一段代码,这段代码是一段错误代码,因为会陷入无穷的循环调用中

public class A
{
B b = new B();

public void invoke()
{
b.Method(this);
}
}

public class B
{
public void Mehtod(A a)
{
a.invoke();
}
}


其实拦截器的实现跟这个方式很像,struts在ActionInvoke上做得很好,所以使整个流程很有逻辑。可以看到,在ActionInvoke的invoke方法中,index扮演者一个非常重要的分流角色,避免与Interceptor之间的陷入无尽的相互调用之中。下面是模拟拦截器的完整代码

class Program
{
static void Main(string[] args)
{
Action a = new Action();
ActionInvocation invoker = new ActionInvocation(a);
invoker.invoke();
Console.ReadLine();
}
}

public class Action
{
public void Execute()
{
Console.WriteLine("Action invoked");
}
}

public interface Interceptor
{
void Intercept(ActionInvocation actionInvocation);
}

public class Interceptor1 : Interceptor
{
public void Intercept(ActionInvocation actionInvocation)
{
Console.WriteLine("=======*1");
actionInvocation.invoke();
Console.WriteLine("=======*-1");
}
}

public class Interceptor2 : Interceptor
{
public void Intercept(ActionInvocation actionInvocation)
{
Console.WriteLine("=======*2");
actionInvocation.invoke();
Console.WriteLine("=======*-2");
}
}

public class ActionInvocation
{

List<Interceptor> interceptors = new List<Interceptor>();
int index = -1;
Action action = null;

public ActionInvocation(Action action)
{
this.action = action;
this.interceptors.Add(new Interceptor1());
this.interceptors.Add(new Interceptor2());
}

public void invoke()
{
index++;
if (index >= this.interceptors.Count)
{
action.Execute();
}
else
{
this.interceptors[index].Intercept(this);
}
}
}
接下来用一张图片对这个流程进行简单的分析



整个的调用过程中

Step1,index=0,调用Interceptor1的Intercept()方法,输出=======*1

Step2,调用actionInvoke的invoke方法

Step3,因为此时index=1,所以继续调用Interceptor2的Intercept()方法,输出======*2

Step4,在Interceptor2的Intercept()方法中,再次回到了actionInvoke的invoke方法,执行action.Execute()

Step5,接着执行Interceptor2的Intercept()中的输出命令,输出======*-2

Step6,回到上一层的调用中,回到Interceptor1的Intercept()中的输出命令,输出=======*-1

至此,这个过程结束。

总体上看,是从invoke()中开始执行到Interceptor1的时候,再次调用invoke方法,就会在Interceptor1的执行区间内,包裹一个Interceptor2执行。当Interceptor2完事后,会继续回到Interceptor1执行剩下的逻辑,这里是输出字符串。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: