C#设计模式:职责链模式(Chain of Responsibility)
一,什么是职责链模式(Chain of Responsibility)
职责链模式是一种行为模式,为解除请求的发送者和接收者之间的耦合,而使多个对象都有机会处理这个请求。将这些对象连接成一条链,并沿着这条链传递该请求,直到有一个对象处理它。
二,如下代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _20.职责链模式 { /// <summary> /// 职责链模式是一种行为模式,为解除请求的发送者和接收者之间的耦合,而使多个对象都有机会处理这个请求。 /// 将这些对象连接成一条链,并沿着这条链传递该请求,直到有一个对象处理它。 /// </summary> class Program { static void Main(string[] args) { People people = AuditorManager.GetAuditor(); people.HandleRequest("中国人"); people.HandleRequest("美国人"); } } /// <summary> /// 管理审核者 /// </summary> public class AuditorManager { private static People AuditorPeople = null; /// <summary> /// 初始化数据 /// </summary> static AuditorManager() { Chinses chinses = new Chinses(); Usa usa = new Usa(); chinses.SetNext(usa); usa.SetNext(chinses); AuditorPeople = chinses; } public static People GetAuditor() { return AuditorPeople; } } /// <summary> /// 抽象审核者 /// </summary> public abstract class People { public People _people { get; private set; } public void SetNext(People people) { this._people = people; } public string Name { get; set; } /// <summary> /// 定义一个处理请求的接口 /// </summary> /// <param name="request"></param> public abstract void HandleRequest(string request); } /// <summary> /// 具体审核者 /// </summary> public class Chinses : People { /// <summary> /// 处理其所负责的请求 /// </summary> /// <param name="request"></param> public override void HandleRequest(string request) { if (request == "中国人") { Console.WriteLine("中国人执行任务"); } else { base._people.HandleRequest(request); } } } /// <summary> /// 具体审核者 /// </summary> public class Usa : People { /// <summary> /// 处理其所负责的请求 /// </summary> /// <param name="request"></param> public override void HandleRequest(string request) { if (request == "美国人") { Console.WriteLine("美国人执行任务"); } else { _people.HandleRequest(request); } } } }