在一些情况下,对一个消息(含事件)的响应和处理需要很多对象来参与,这些对象对消息的处理有前后顺序,形成一个处理链条,但对象是否真正处理消息有赖于在它之前的对象的处理策略,前一个对象处理后,后一个对象则不需参与处理,这就是责任链模式。现实中有很多类似的场景,比如上访,上访一般是从最基层的信访部门接受信访开始进行处理,如果下一级信访部门无法处理,则交给上一级部门进行处理,这样一级一级的处理,知道最高信访部门。这样所有层级的信访部门就构成了一个责任链。
public abstract class Chain_Successor { protected Chain_Successor successor; //保存后继责任者的引用 /// <summary> /// 处理需求 /// </summary> /// <param name="request">需要处理的类</param> public abstract void HandleReqest(Chain_Request request); /// <summary> /// 设置后继责任者 /// </summary> /// <param name="successor">后继责任者</param> public void SetChain_Successor(Chain_Successor successor) { this.successor = successor; } } public class Chain_ConcreateHandleA : Chain_Successor { public Chain_ConcreateHandleA() { } public override void HandleReqest(Chain_Request request) { //如果自己能处理则处理,否则传递给后继者 if(request.Request_Type==1) { System.Windows.Forms.MessageBox.Show(this.ToString()+":"+request.Request_Parameters); } else { if(this.successor!=null) successor.HandleReqest(request); } } } public class Chain_ConcreateHandleB : Chain_Successor { public Chain_ConcreateHandleB() { } public override void HandleReqest(Chain_Request request) { //如果自己能处理则处理,否则传递给后继者 if(request.Request_Type==2) { System.Windows.Forms.MessageBox.Show(this.ToString()+":"+request.Request_Parameters); } else { if(this.successor!=null) successor.HandleReqest(request); } } } public class Chain_ConcreateHandleC : Chain_Successor { public Chain_ConcreateHandleC() { } public override void HandleReqest(Chain_Request request) { //如果自己能处理则处理,否则传递给后继者 if(request.Request_Type==3) { System.Windows.Forms.MessageBox.Show(this.ToString()+":"+request.Request_Parameters); } else { if(this.successor!=null) successor.HandleReqest(request); } } } public class Chain_Request { //下面的两个参数可更加具体需要进行构造 private int _Request_type; private string _Request_parameters; public Chain_Request(int Request_type,string RequestParameters) { this._Request_type = Request_type; this._Request_parameters = RequestParameters; } public int Request_Type { get { return _Request_type; } set { _Request_type = value; } } public string Request_Parameters { get { return _Request_parameters; } set { _Request_parameters = value; } } } public class Chain_Client { public static void Test() { Chain_Successor firstHandler = new Chain_ConcreateHandleA(); Chain_Successor secondHandler = new Chain_ConcreateHandleB(); Chain_Successor ThirdHandler = new Chain_ConcreateHandleC(); firstHandler.SetChain_Successor(secondHandler); secondHandler.SetChain_Successor(ThirdHandler); firstHandler.HandleReqest(new Chain_Request(2,"hello,the world!")); } }