行为型设计模式
责任链模式
转移行为
请求的处理流程,沿着链子顺序执行,还允许链子扩展和订制
以请假为例子
请假申请类
/// <summary>
/// 请假申请,
/// Context--上下文环境,保存业务处理中参数-中间结果-最终结果
/// 行为型设计模式常用的标配
/// 把行为转移,
/// </summary>
public class ApplyContext
{
public int Id { get; set; }
public string Name { get; set; }
/// <summary>
/// 请假时长
/// </summary>
public int Hour { get; set; }
public string Description { get; set; }
public bool AuditResult { get; set; }
public string AuditRemark { get; set; }
}
抽象类
public abstract class AbstractAuditor
{
public string Name { get; set; }
public abstract void Audit(ApplyContext context);
private AbstractAuditor _NextAuditor = null;
public void SetNext(AbstractAuditor auditor)
{
this._NextAuditor = auditor;
}
protected void AuditNext(ApplyContext context)
{
if (this._NextAuditor != null)
{
this._NextAuditor.Audit(context);
}
else
{
context.AuditResult = false;
context.AuditRemark = "不允许请假!";
}
}
}
业务类
/// <summary>
/// 职责问题:
/// 1 权限范围内,审批通过
/// 2 权限范围外,交给下一环节审批
/// 写的代码又多了一个,指定下一环节
/// 甩锅大法
/// </summary>
public class PM : AbstractAuditor
{
public override void Audit(ApplyContext context)
{
Console.WriteLine($"This is {this.GetType().Name} {this.Name} Audit");
if (context.Hour <= 8)
{
context.AuditResult = true;
context.AuditRemark = "允许请假!";
}
else
{
base.AuditNext(context);
}
}
}
public class Manager : AbstractAuditor
{
public override void Audit(ApplyContext context)
{
Console.WriteLine($"This is {this.GetType().Name} {this.Name} Audit");
if (context.Hour <= 24)
{
context.AuditResult = true;
context.AuditRemark = "允许请假!";
}
else
{
base.AuditNext(context);
}
}
}
public class Chief : AbstractAuditor
{
public override void Audit(ApplyContext context)
{
Console.WriteLine($"This is {this.GetType().Name} {this.Name} Audit");
if (context.Hour <= 48)
{
context.AuditResult = true;
context.AuditRemark = "允许请假!";
}
else
{
base.AuditNext(context);
}
}
}
封装给上层调用的类
public class AuditorBuilder
{
/// <summary>
/// 那就反射+配置文件
/// 链子的组成都可以通过配置文件
/// </summary>
/// <returns></returns>
public static AbstractAuditor Build()
{
AbstractAuditor pm = new PM()
{
Name = "斗帝"
};
AbstractAuditor manager = new Manager()
{
Name = "橙"
};
AbstractAuditor chief = new Chief()
{
Name = "Tenk"
};
pm.SetNext(manager);
manager.SetNext(chief);
return pm;
}
}
上层调用
AbstractAuditor auditor = AuditorBuilder.Build();
auditor.Audit(context);
if (!context.AuditResult)
{
Console.WriteLine("不干了!");
}
这样处理,保证了下层的稳定,把不稳定的行为转移到上层