职责链模式(Chain of Responsibility Pattern):避免请求发送者与接收者耦合在一起,让多个对象都有可能接收请求,将这些对象连接成一条链,并且沿着这条链传递请求,直到有对象处理它为止。
模式角色与结构:
示例代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CSharp.DesignPattern.ResponsibilityChainPattern { class Program { static void Main(string[] args) { // 需要注意,职责链模式并不创建职责链,职责链的创建工作必须由系统的其他部分来完成, // 一般是在使用该职责链的客户端中创建职责链。 Handler annal = new Director(); Handler tony = new VicePresident(); Handler marc = new President(); Handler meeting = new Congress(); annal.SetSuccessor(tony); tony.SetSuccessor(marc); marc.SetSuccessor(meeting); Console.WriteLine("Request: President"); annal.HandleRequest("President"); Console.ReadLine(); } } // 抽象处理类 abstract class Handler { protected Handler successor; // 维持对下家的引用 public void SetSuccessor(Handler successor) { this.successor = successor; } public abstract void HandleRequest(String request); } // 具体处理类 class Director : Handler { public override void HandleRequest(string request) { if (request == "Director") { Console.WriteLine("Director Handle..."); } else { this.successor.HandleRequest(request); // 体现职责链 } } } // 具体处理类 class VicePresident : Handler { public override void HandleRequest(string request) { if (request == "VicePresident") { Console.WriteLine("VicePresident Handle..."); } else { this.successor.HandleRequest(request); // 体现职责链 } } } // 具体处理类 class President : Handler { public override void HandleRequest(string request) { if (request == "President") { Console.WriteLine("President Handle..."); } else { this.successor.HandleRequest(request); // 体现职责链 } } } // 具体处理类 class Congress : Handler { public override void HandleRequest(string request) { if (request == "Congress") { Console.WriteLine("Congress Handle..."); } else { this.successor.HandleRequest(request); // 体现职责链 } } } }