0

I am thinking about the chain of responsibility pattern, and cannot understand a few things:

  1. Can handlers be conditional? Like if (foo) { callHandlerA() } else { callHandlerB() }, or they must be inline (i.e. always call next handler it current cannot handle the request?)?

  2. If handlers handled a request, can it break call chain? It seems like, yes, because it is handling also, but instead of doing something, it just doing nothing.

  3. In general, I see it is the same thing as calling handlers directly, i.e.

function doItHandlingMaster(data) {
  if (handlerA(data)) {
    return;
  }
  if (handlerB(data)) {
    return;
  }
  if (handlerC(data)) {
    return;
  }
  ... and so on
}

so the main ideas of the pattern are flexibility (we can define steps once and reuse them) and louse coupling (we know only about the entrance, and do not know all handling steps), right?

I saw this pattern many times (Express, DOM, Angular, almost everywhere), and want to understand it clearly.

Thanks!

  • https://stackoverflow.com/questions/55979891/is-chain-of-responsibility-pattern-just-an-overkill-a-list-of-handlers-can-acc/55982711#55982711 – Matt Timmermans Sep 02 '19 at 14:40

1 Answers1

1
  1. Choice handlers in another handler with help conditions are bad practice because it makes hard dependencies between different handlers.
  2. Yes, If handlers handled a request chain of calls might be broken.
  3. You are right. The main idea of chain of responsibility pattern is flexibility and keeping of low coupling between different classes
Maksym Fedorov
  • 6,383
  • 2
  • 11
  • 31