在C#中,责任链模式(Chain of Responsibility Pattern)是一种行为型设计模式,它可让多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。请求沿着一个链传递,直到有一个对象处理它为止。
责任链模式有以下几个关键角色:
Handler(处理器):定义处理请求的接口,并通常持有一个指向下一个处理器的引用。
ConcreteHandler(具体处理器):实现处理请求的接口,并决定是否能够处理该请求,如果不能处理则将请求传递给下一个处理器。
下面是一个示例,展示如何在C#中使用责任链模式来实现一个简单的请假审批系统:
namespace ChainOfResponsibilityPattern_责任链模式
{
public class ChainOfResponsibility
{
public abstract class LeaveRequestHandler
{
protected LeaveRequestHandler NextHandler;
public void SetNextHandler(LeaveRequestHandler nextHandler)
{
NextHandler = nextHandler;
}
public abstract void HandleRequest(LeaveRequest request);
}
// ConcreteHandler
public class SupervisorHandler : LeaveRequestHandler
{
public override void HandleRequest(LeaveRequest request)
{
if (request.Days <= 3)
{
Console.WriteLine("Leave request approved by supervisor");
}
else if (NextHandler != null)
{
NextHandler.HandleRequest(request);
}
}
}
public class ManagerHandler : LeaveRequestHandler
{
public override void HandleRequest(LeaveRequest request)
{
if (request.Days <= 5)
{
Console.WriteLine("Leave request approved by manager");
}
else if (NextHandler != null)
{
NextHandler.HandleRequest(request);
}
}
}
public class HRHandler : LeaveRequestHandler
{
public override void HandleRequest(LeaveRequest request)
{
if (request.Days <= 7)
{
Console.WriteLine("Leave request approved by HR");
}
else
{
Console.WriteLine("Leave request denied");
}
}
}
// LeaveRequest
public class LeaveRequest
{
public int Days { get; set; }
}
}
}
namespace ChainOfResponsibilityPattern_责任链模式
{
internal class Program
{
static void Main(string[] args)
{
LeaveRequestHandler supervisor = new SupervisorHandler();
LeaveRequestHandler manager = new ManagerHandler();
LeaveRequestHandler hr = new HRHandler();
supervisor.SetNextHandler(manager);
manager.SetNextHandler(hr);
LeaveRequest request = new LeaveRequest { Days = 2 };
supervisor.HandleRequest(request);
request = new LeaveRequest { Days = 6 };
supervisor.HandleRequest(request);
request = new LeaveRequest { Days = 10 };
supervisor.HandleRequest(request);
Console.Read();
//输出结果
//Leave request approved by supervisor
//Leave request approved by HR
//Leave request denied
}
}
}
通过使用责任链模式,可以让多个对象都有机会处理请求,避免请求发送者和接收者之间的紧耦合关系。可以根据实际需求创建不同的责任链,并按照顺序进行处理。此外,责任链模式还具有灵活性,可以动态地改变链中的处理顺序或添加新的处理器。
标签:supervisor,request,模式,责任,ChainOfResponsibilityPattern,LeaveRequestHandler,new,Le From: https://www.cnblogs.com/ZHIZRL/p/17647739.html