Search code examples
design-patternschain-of-responsibility

Chain of Responsibility


Why I need to use CoR if I could write if-else and instead of passing through multiple handlers I could just find whatever handler I need and delegate the processing to the specific one.

I think, CoR is not being used as a pipeline to process the same request in multiple handlers (like this: https://github.com/RichJones22/chainOfResponsibility_cpp/blob/master/main.cpp). So why I use CoR at all?


Solution

  • What are the advantages of CoR?

    You are correct that it is a kind of pipeline; each step of the pipeline interacts with the next step through the base class interface. You can use it if each of the pipeline steps do not depend on/are tied in with the context of the previous steps directly.

    Each class would implement its own stage of the pipeline, advantages are:

    • modularization: each pipeline class treats its well defined aspect/command; the code of each command object/pipeline stage is supposed to be cleaner and easier to read/maintain.

    • one advantage is that you can debug/test each of these classes separately, independent from the rest of the command/pipeline classes; this is great if you have unit tests.

    • you can configure different instances of pipelines in a factory/builder class and treat the command classes as building blocks and stack them up depending on configuration/actual requirements.

      one example is a logging stage; you would add a derived class that just does logging and add it to the end of the pipeline, i an event must be logged; if you are in a 'no logging mode configuration' then you will not stack up this command object.