责任链模式是一种对象行为型模式,其避免请求的发送者与多个请求的处理者紧密耦合,将所有的请求通过链式的结构,前一个对象引用后一个对象。当有请求发出时,请求将会沿着链进行传播最终被需要执行的对象处理。以公司请假为例,请假3天以内,部门经理批准,请假3到7天,需要总监批准,请教超过7天需要CEO批准,员工只需要告诉责任链要请假几天,责任链会让有权限的审批者处理。
namespace Designmode.ChainOfResponsibility
{
/// <summary>
/// 审批者的抽象类
/// </summary>
public abstract class Approver
{
/// <summary>
/// 下一个审批者
/// </summary>
protected Approver _nextHandler = null;
/// <summary>
/// 请求方法
/// </summary>
/// <param name="days">请假的天数</param>
public abstract void Request(int days);
/// <summary>
/// 设置下一个审批者
/// </summary>
/// <param name="approver">下一个审批者</param>
public Approver SetNext(Approver approver)
{
this._nextHandler = approver;
return approver;
}
/// <summary>
/// 获取下一个审批者
/// </summary>
/// <param name="approver">下一个审批者</param>
public Approver GetNext()
{
return this._nextHandler;
}
}
}
namespace Designmode.ChainOfResponsibility
{
/// <summary>
/// 部门经理
/// </summary>
public class DepartmentManager : Approver
{
/// <summary>
/// 请假
/// </summary>
/// <param name="days"></param>
public override void Request(int days)
{
if (0 < days && days <= 3)
{
Console.WriteLine("部门经理批准请假");
}
else
{
this._nextHandler?.Request(days);
}
}
}
}
namespace Designmode.ChainOfResponsibility
{
/// <summary>
/// 部分总监
/// </summary>
public class DepartmentDirector : Approver
{
/// <summary>
/// 请假
/// </summary>
/// <param name="days"></param>
public override void Request(int days)
{
if (3 < days && days <= 7)
{
Console.WriteLine("部门总监批准请假");
}
else
{
this._nextHandler?.Request(days);
}
}
}
}
namespace Designmode.ChainOfResponsibility
{
/// <summary>
/// CEO
/// </summary>
public class CEO : Approver
{
/// <summary>
/// 请假
/// </summary>
/// <param name="days"></param>
public override void Request(int days)
{
if (days > 7)
{
Console.WriteLine("CEO批准请假");
}
else
{
this._nextHandler?.Request(days);
}
}
}
}