lundi 15 avril 2019

Is it feasible to use publish-subscribe pattern with one publisher and one subscriber?

I don't know if I should use publish-subscribe (seems sexy to me now, but later..), observer or DI and call methods. I have two situations:

  • (A) one class produces an "event" which should run code from a different class (data has changed - recalculate something)
  • (B) one class calls a method form another class and needs to run code when something happens within the called method after the called method returned (execute this code when you finish part of a task because I need to modify my internal state)

Options:

  1. Create some kind of event bus, one class subscribes to a topic, another class publishes something to it. There is one publisher, one subscriber. Things are decoupled. Harder to navigate and figure out what calls what when.
  2. Create a list of observers (with one observer) in the "event" class and notify it. The list contains interfaces (or is something like an event in C#). The class being notified needs to know where to add itself (as an observer). Not as decoupled as previous, no need for any event bus.
  3. Use DI to inject the instance which needs to be notified directly into the "publisher" and call some method. Simple, slightly more coupled?
  4. A callback is passed from one class to another either during some kind of initialization (A) or during method call (B) (is passing a callback to another method to be called when needed ok?)

    Just want to add the system is being changed very rapidly, it's more of a proof of concept or a prototype.

Aucun commentaire:

Enregistrer un commentaire