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.