【设计模式】之责任链模式

  • UML

【设计模式】之责任链模式_第1张图片
  • 举例

//处理请示的接口
    abstract class Handler
    {
        protected Handler successor;
        public void SetSuccessor(Handler successor)
        {
            this.successor = successor;
        }
        public abstract void HandleRequest(int request);
    }
//处理者1
    class ConcreteHandler1:Handler
    {
        public override void HandleRequest(int request)
        {
            if (request >= 0 && request < 10)
            {
                Console.WriteLine("{0}处理请求{1}", this.GetType().Name, request);
            }
            else if (successor !=null)
            {
                successor.HandleRequest(request);
            }
        }
    }
 //处理者2
    class ConcreteHandler2 : Handler
    {
        public override void HandleRequest(int request)
        {
            if(request>=10&&request<20)
            {
                Console.WriteLine($"{this.GetType().Name}处理请求{request}");
            }else if(successor!=null)
            {
                successor.HandleRequest(request);
            }
        }
    }
class Program
    {
        static void Main(string[] args)
        {
            ConcreteHandler1 concreteHandler1 = new ConcreteHandler1();
            ConcreteHandler2 concreteHandler2 = new ConcreteHandler2();
            concreteHandler1.SetSuccessor(concreteHandler2);
            string con = Console.ReadLine();
            int num = Convert.ToInt32(con);
            concreteHandler1.HandleRequest(num);
        }
    }

你可能感兴趣的:(《大话设计模式》学习笔记)