zoukankan      html  css  js  c++  java
  • 设计模式:职责链模式

    职责链模式(Chain of Responsibility):使多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。

    namespace ChainDesign
    {
        public abstract class Handler
        {
            protected Handler successor;
            public void SetSuccessor(Handler successor)
            {
                this.successor = successor;
            }
            public abstract void HandleRequest(int request);
        }
        public 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);
                }
            }
        }
        public class ConcreteHandler2 : Handler
        {
            public override void HandleRequest(int request)
            {
                if (request >= 10 && request < 20)
                {
                    Console.WriteLine("{0}处理请求{1}", this.GetType().Name, request);
                }
                else if (successor != null)
                {
                    successor.HandleRequest(request);
                }
            }
        }
        public class ConcreteHandler3 : Handler
        {
            public override void HandleRequest(int request)
            {
                if (request >= 20 && request < 30)
                {
                    Console.WriteLine("{0}处理请求{1}", this.GetType().Name, request);
                }
                else if (successor != null)
                {
                    successor.HandleRequest(request);
                }
            }
        }
    }
    View Code

    测试代码:

                Handler h1 = new ConcreteHandler1();
                Handler h2 = new ConcreteHandler2();
                Handler h3 = new ConcreteHandler3();
                h1.SetSuccessor(h2);
                h2.SetSuccessor(h3);
                int[] requests = { 2, 5, 14, 22, 18, 3, 27, 20 };
                foreach(int request in requests)
                {
                    h1.HandleRequest(request);
                }
    View Code
  • 相关阅读:
    .NET XmlNavigator with Namespace
    编程要素
    【FOJ】1962 新击鼓传花游戏
    【POJ】1389 Area of Simple Polygons
    【POJ】2482 Stars in Your Window
    【HDU】3265 Posters
    【HDU】1199 Color the Ball
    【HDU】3642 Get The Treasury
    【HDU】4027 Can you answer these queries?
    【HDU】1542 Atlantis
  • 原文地址:https://www.cnblogs.com/uptothesky/p/5286415.html
Copyright © 2011-2022 走看看