I have a large number of instances of a class. Those instances can fire an event. The only important thing for that event is which instance fired it.I have another instance of a class (and maybe in the future more classes), that want to subscribe to that event.For example (in pseudo C#):class Button{   public event EventHandler<Button> PressedTheButtonEvent();}class EventConsumer{   private int buttonsPressed;   private OnButtonPressed(Button buttonReference)   {      buttonReference.color = blue;      buttonsPressed++;   }}In order for the EventConsumer class to subscribe to the event, it needs to subscribe to every instance's EventHandler<Button> delegate. Given the fact, that I have a large number of buttons, I do not like iterating over every existing button and susbcribing. This is prone to errors, especially if, for some reason, a button is created, after I have iterated over them.I have come up with 2 solutions:Make the PressedTheButtonEvent static.Create another class, that has a single event. Instead of every button firing its event, call a method on the new class to do so.I don't like 2. because the new class is tightly coupled with the Button class.I also don't like much 1., because if for some reason, someone forgets to unsubscribe from the static event, those instances will not be garbage collected.Are there any other solutions?I'm writing C#, but I tried to keep the question in a more general context.
Proper event driven design when a consumer subscribes to many producers
class design;event programming;coupling
2 is the mediator pattern. You can get around the tight coupling by:Injecting a IMediator interface with just 'publish' and 'listen'By using a factory method to create the buttons and wire up the event at the same timeHave a ButtonViewModel which takes the injected mediator, the event and wires up to the ButtonView which contains the button.If you are doing C# with wpf the viewmodel is the way to go