{C#}设计模式辨析.责任链
作者:
码农猫爸 | 来源:发表于
2021-08-09 07:51 被阅读0次背景
示例
using static System.Console;
namespace DesignPattern_ChainOfResponsibility
{
// 接口,确保层级间互换
public interface IHandler
{
IHandler SetNext(IHandler next); // 设置下级组成责任链,流畅格式(类似lambda)
void Handle(decimal cost); // 按职权处理
}
// 抽象类,包含公共(默认)代码
public abstract class Handler : IHandler
{
private IHandler next;
private readonly decimal limit;
public Handler(decimal limit)
{
this.limit = limit;
}
public virtual void Handle(decimal cost)
{
// 最后一人 或职权范围内
if (next == null || cost >= limit)
{
WriteLine($"Cost of {cost}RMB is handled by {GetType().Name}.");
return;
}
next.Handle(cost);
}
public IHandler SetNext(IHandler next)
{
this.next = next;
return next;
}
}
// 总裁类,责任链入口
public class President : Handler
{
public President(decimal limit) : base(limit) { }
}
// 经理类
public class Manager : Handler
{
public Manager(decimal limit) : base(limit) { }
}
// 文员类
public class Clerk : Handler
{
public Clerk(decimal limit) : base(limit) { }
}
class Program
{
static void Main(string[] args)
{
var president = new President(1000_0);
president
.SetNext(new Manager(1000))
.SetNext(new Clerk(-1));
president.Handle(2000_0);
president.Handle(2000);
president.Handle(200);
ReadKey();
}
}
}
本文标题:{C#}设计模式辨析.责任链
本文链接:https://www.haomeiwen.com/subject/uugnvltx.html
网友评论