C# 设计模式(15)责任链模式
责任链模式
1.逻辑封装和转移
代码实现:
上下文:
public class ApplyContext { public int Id { get; set; } public string Name { get; set; } public int Hour { get; set; } public string Description { get; set; } public string AuditRemark { get; set; } public bool AuditResult { get; set; } }
抽象类:
public abstract class AbstractAuditor { private AbstractAuditor _nextAuditor = null; public void SetNextAuditor(AbstractAuditor nextAuditor) { _nextAuditor = nextAuditor; } public abstract void Audit(ApplyContext applyContext); protected void NextAudit(ApplyContext applyContext) { if (_nextAuditor != null) { _nextAuditor.Audit(applyContext); } } }
实体类:
public class PM : AbstractAuditor { public override void Audit(ApplyContext applyContext) { if(applyContext.Hour<8) { applyContext.AuditResult = true; Console.WriteLine("PM 审核完成!享受你的假期吧"); } else { base.NextAudit(applyContext); } } } public class Charge : AbstractAuditor { public override void Audit(ApplyContext applyContext) { if(applyContext.Hour<16) { applyContext.AuditResult = true; Console.WriteLine("主管 审核完成!享受你的假期吧"); } else { base.NextAudit(applyContext); } } } public class Manager : AbstractAuditor { public override void Audit(ApplyContext applyContext) { if(applyContext.Hour<24) { Console.WriteLine("经理 审核完成!享受你的假期吧"); } else { base.NextAudit(applyContext); } } }
代码调用:
class Program { static void Main(string[] args) { ApplyContext applyContext = new ApplyContext() { Id = 01, Name = "Alex", Hour = 12, Description = "Vacation", AuditResult = false, AuditRemark = "" }; PM pM = new PM(); Charge charge = new Charge(); Manager manager = new Manager(); pM.SetNextAuditor(manager); pM.Audit(applyContext); } }
结果: