Search code examples
eventsdesign-patternschain-of-responsibility

Chain of Responsibility vs Events


I always have a doubt when to choose one of these 2 patterns. For example: Let's assume that I have an input manager and when I press the one button, I want the main player to execute the jump action. In this case, I can use 2 different solutions:

  1. I have one inputManager that tells the GameManager what just append and the gameManager tells the Player-manager to act. So it's something like: inputManager ---> Game manager ---> Player-manager and this is the Chain of Responsibility pattern.
  2. the PlayerManager registers the jump event on the inputManager to receive the input and the PlayerManager automatically executes its jump routine.

So my question is: Why would I choose one pattern over the other? Both have their pro and cons, so which is your preferred solution when you have this kind of situation?


Solution

  • The key here is the term responsibility:

    1. The GameManager has the responsibility of commanding the PlayerManager to perform the jump. This suggests that the logic is centralized in the GameManager, enabling complex orchestrations: it seems likely that the GameManager will command a number of other managers and that it may do so by performing some logic taking all of them into account.

    2. The PlayerManager takes the decision on its own, based on received events. In this approach, the logic is decentralized: each stakeholder will listen for the events it is interested in and act accordingly. Hence, each one will be responsible for its actions. The GameManager has no part in it and may be just as important an stakeholder as PlayerManager: they most likely will not know that the other exists and there is no hierarchy implied, each one just works in isolation.