lundi 2 septembre 2019

Chain of Responsibility, what exactly does this pattern mean?

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!

Aucun commentaire:

Enregistrer un commentaire