职责链模式(Chain of Responsibility)
定义
职责链模式(Chain of Responsibility),使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
类图
描述
Handler,定义一个处理请求的接口;
ConcreteHandler,具体处理者类,处理它所负责的请求,可访问它的后继者,如果可以处理该请求,就处理;否则就将该请求转发给它的后继者。
应用场景
公司规定,员工请假在2天以内(<2天)由部门经理批准,3天以内(<3天)由部门总监批准,超过3天(>=3天)由boss批准。
public abstract class Handler { private string name; /// <summary> /// 管理者的名字 /// </summary> public string Name { get { return name; } } /// <summary> /// 管理者的上级 /// </summary> protected Handler superior; public Handler(string name) { this.name = name; } public void SetSuperior(Handler superior) { this.superior = superior; } public abstract void HandeRequest(Request request); } public class Request { private string name; /// <summary> /// 请假者的姓名 /// </summary> public string Name { get { return name; } set { name = value; } } private double days; /// <summary> /// 请假天数 /// </summary> public double Days { get { return days; } set { days = value; } } } /// <summary> /// 经理 /// </summary> public class Manager : Handler { public Manager(string name) : base(name) { } public override void HandeRequest(Request request) { if (request.Days > 0 && request.Days < 2) { Console.WriteLine(this.Name + "批准了" + request.Name + "的" + request.Days + "天假期."); } else { if (this.superior != null) { this.superior.HandeRequest(request); } } } } /// <summary> /// 总监 /// </summary> public class Majordomo:Handler { public Majordomo(string name) : base(name) { } public override void HandeRequest(Request request) { if (request.Days > 0 && request.Days < 3) { Console.WriteLine(this.Name + "批准了" + request.Name + "的" + request.Days + "天假期."); } else { if (this.superior != null) { this.superior.HandeRequest(request); } } } } public class Boss : Handler { public Boss(string name) : base(name) { } public override void HandeRequest(Request request) { Console.WriteLine(this.Name + "批准了" + request.Name + "的" + request.Days + "天假期."); } }