设计模式之责任链模式(八)

   定义一系列的实现类和一个数据上下文context。实现类相互关联,形成一个链式结构,实现类根据上下文中的枚举值或者范围值定义不同的操作。处理流程按照链路来进行,可以对链路进行扩展或定制

例如请假时间<=3天的,第一个实现类(项目经理)处理。请假时间<=7天的,第一个实现类转交给第二个实现类(开发主管)处理。请假时间>=7天的,第二个实现类转交给第三个实现类(总经理)处理。

//审核上下文
    public class AuditContext
    {
        //请假时长
        public int Hour { get; set; }
        //请假人
        public string Name { get; set; }
    }


    public interface IAuditor
    {
        void Audit(AuditContext context);
    }
    //项目经理审核
    public class PMAuditor:IAuditor
    {
        private readonly IAuditor _nextAuditor = null;
        public PMAuditor(IAuditor nextAuditor)
        {
            this._nextAuditor = nextAuditor;
        }
        public void Audit(AuditContext context)
        {
            if (context.Hour > 0 && context.Hour <= 8*3)
            {
                //审核逻辑
            }
            else
            {
                if (_nextAuditor != null)
                    _nextAuditor.Audit(context);
            }
        }
    }

    //主管审核
    public class SupervisorAuditor : IAuditor
    {
        private readonly IAuditor _nextAuditor = null;
        public SupervisorAuditor(IAuditor nextAuditor)
        {
            this._nextAuditor = nextAuditor;
        }
        public void Audit(AuditContext context)
        {
            if (context.Hour > 8*3 && context.Hour <= 8*7)
            {
                //审核逻辑
            }
            else
            {
                if (_nextAuditor != null)
                    _nextAuditor.Audit(context);
            }
        }
    }

    //总经理审核
    public class GMAuditor : IAuditor
    {
        private readonly IAuditor _nextAuditor = null;
        public GMAuditor(IAuditor nextAuditor)
        {
            this._nextAuditor = nextAuditor;
        }
        public void Audit(AuditContext context)
        {
            if (context.Hour >= 8*7)
            {
                //审核逻辑
            }
            else
            {
                if (_nextAuditor != null)
                    _nextAuditor.Audit(context);
            }
        }
    }

客户端使用:


 IAuditor auditorGM = new GMAuditor(null);
 IAuditor auditorSupervisor = new SupervisorAuditor(auditorGM);
 IAuditor auditorPM = new PMAuditor(auditorSupervisor);

 auditorPM.Audit(new AuditContext() { Hour = 8*10});

 

你可能感兴趣的:(设计模式,系统架构,设计原则)