首页 > 其他分享 >责任链模式

责任链模式

时间:2023-06-03 21:47:03浏览次数:37  
标签:handle handler request 模式 责任 Handler nextHandler public

The Chain of Responsibility design pattern avoids coupling the sender of the request to its receiver by giving more than one object a chance to handle the request. This pattern chains the receiving objects and passes the request along the chain until an object handles it.

责任链模式避免发送者和接受者耦合,给每个对象机会处理请求,此模式将接收对象连接起来,并沿着该链传递请求直到处理它为止。

In simple words, we can say that the chain of responsibility desgin pattern creates a chain of receiver objects for given request. In this design pattern, normally each receiver contains a reference to another receiver. If one receiver cannot handle the request then it passes the same request to the next receiver and so on.One receiver hanldes the request in the chain or one or more receivers handle the request.

 

UML Calss Diagram

 Handler: this is going to be an abstract class that deines how the request is going to be handled. It contains a member that holds the next handler in the chain and an associated method to set thhis next handler. It also has an abstract method that is going to be implemented by concrete handler classes to handle the incoming request as well as if required then it will pass the request to the next handler object in the pipeline. 

  ConcreteHandler: this is going to be concrete classes that is inherited from handler abstract class and provide implementations for the abstract method. This method has the logic to handle the request. And if required, then it will forward the request to the next handler associated tin the pipeline.

  Client: This is the class that generates the request and passes it to the first handler in the chain of responsibility.

 

Structure Code in C#

public abstract class Handler
    {
        protected Handler nextHandler;
        public void SetNextHandler(Handler nextHandler)
        { 
            this.nextHandler = nextHandler; 
        }
        public abstract void HandleRequest(int request);
    }
Handler
 public class ConcreteHanderA : Handler
    {
        public override void HandleRequest(int request)
        {
            if (request >= 0 && request < 10)
                Console.WriteLine($"{this.GetType().Name} handled request {request}.");
            else if (nextHandler != null)
                nextHandler.HandleRequest(request);
        }
    }

    public class ConcreteHanderB : Handler
    {
        public override void HandleRequest(int request)
        {
            if (request >= 10 && request < 20)
                Console.WriteLine($"{this.GetType().Name} handled request {request}.");
            else if (nextHandler != null)
                nextHandler.HandleRequest(request);
        }
    }

    public class ConcreteHanderC : Handler
    {
        public override void HandleRequest(int request)
        {
            if (request >= 20 && request < 30)
                Console.WriteLine($"{this.GetType().Name} handled request {request}.");
            else if (nextHandler != null)
                nextHandler.HandleRequest(request);
        }
    }
ConcreteHandler

When to use Chain of Responsibility Design Pattern in Real-Time Application?

  • A set of handlers are used in the pipeline to handle the request.
  • You need to pass a request to one handler at run-time based on certain conditions.
  • Exception Handling in C# is one of the best example of the chain for responsibility design pattern.When an exception is thrown from the try block, then that excpetion might be going to handle by a corresponding catch block. Here, you can have more than one catch block. Here the catch blocks will behave like handlers to handle exception.

标签:handle,handler,request,模式,责任,Handler,nextHandler,public
From: https://www.cnblogs.com/qindy/p/17414680.html

相关文章

  • 命令模式
    TheCommanddesignpatternencapsulatesarequestasanobject,therebylettingyouparamizeclientswithdifferentrequests,queueorlogrequests,andsupportundoableoperations.命令模式封装请求作为一个对象,因此让你参数化客户端用不同的requests,队列或者日志r......
  • 解释器模式
    Givealanguage,theInterpreterdesignpatterndefinesarepresentationforitsgrammaralongwithaninterpreterthatusestherepresentationtointerpretsentencesinthelanguage.TheInterpreterDesignPatternprovidesawaytoevaluatelanguagegram......
  • 组合模式
    TheCompositedesignpatterncomposesobjectsintotreestructurestorepresentpart-wholehierarchies.Thispatternletsclientstreatindividualobjectandcompositionsofobjectsuniformly.组合模式将对象组合成tree结构代表部分-整体层次结构,这种模式允许客户......
  • 装饰器模式
    TheDecoratorDesignPatternattachesadditionalresponsibilitiestoanobjectdynamically.Thispatternprovideaflexiblealternativetosubclassingforextendingfunctionality.装饰器模式动态的给Object添加额外的职责,这个模式为SubClassing提供灵活的扩展功能。......
  • 外观模式
    TheFacade designpattenprovidesaunifiedinterfacetoasetofinterfacesinasubsystem.Thispatterndefinesahigher-levelinterfacethatmakesthesubsystemeasiertouse.外观模式为子系统一组接口提供了统一的接口,这种模式定义了高级接口,便于子系统调用。......
  • 适配器模式
    TheAdpativedesignpatternconvertstheinterfaceofaclasstoanotherinterfaceclientsexpect.Thisdesignpatternletsclassesworktogetherthatcouldn'totherwisebecauseofincompatibleinterfaces.适配器模式将类的接口转换为客户期望的另外一个接口,这种......
  • 桥接模式
    TheBridgedesignpatterndecouplesanabstractionfromitsimplementationsothathetwocanvaryindependently.桥接模式将抽象和实现解耦,以便两者可以独立变化。UMLClassDiagram Abstraction:definestheabstraction'sinterface;matainsareferencetoanobj......
  • 模板方法模式
    TheTemplateMethoddesignpatterndefinestheskeletonofanalgorithminanoperation,deferingsomestepstosubclasses.Thispatternletssubclassesredefinecertainstepsofanalgorithmwihoutchangingthealgorithm'sstructure.模板方法设计模式在操作中......
  • 创建型设计模式
    TheCreationalDesignPatternareCategorizedintotwotypes. Object-CreationalPatterns:Object-CreationalPatternsdealwithobjectcreation.Here,itdeferspartofitsobjectcreationtoanotherobject.Class-CreationalPatterns:Class-CreationalPa......
  • 策略模式
    TheStrategydesignpatterndefinesafamiliyofalgorithms,encapsulateeachone,andmaketheminterchangeable.Thispatternletsthealgorithmvaryindependentlyfromclientthatuseit.策略模式定义一系列算法,封装它,使他们可以互换,这种设计模式使算法独立于客......