I have what I think is a simple "problem" to which I have found a couple of solutions but I am not sure which way to go andn the best practice in C#.
I have a master object (say a singleton) instanciated once during the lifespan of the application. This "MasterClass" creates a bunch of new type of objects, say "SlaveClass" every time MasterClass.Instance.CreateSlaveObject is called.
This MasterClass also monitors some other object for status change, and when that happens, notifies the SlaveClass objects it created of the change. Seems simple enough.
Since I come from the native C++ world, the way I did it first it to have an interface
Interface IChangeEventListener
{
void ChangeHappened();
}
from which I derived "SlaveClass". Then in my "MasterClass" i have:
...
IList<IChangeEventListener> slaveList;
...
CreateSlaveObject
{
...
slaveList.Add(slave);
}
...
ChangeHappened()
{
...
foreach(var slave in slaveList)
{
slave.ChangeHappened();
}
}
And this works. But I kept wondering in the back of my mind if there is another (better) way of doing this. So I researched a bit more on the topic and saw the C# events.
So instead of maintaining a collection of slaves in the MasterClass, I would basically inject the MasterClass into the ctor of SlaveClass (or via a property) and let the SlaveClass object add it's ChangeHappened as an event handler. this would be illustrated:
...Master...
public delegate void ChangeHappenedDelegate(object sender, NewsInfoArgs args);
public event NewUpdateDelegate ChangeHappenedEvent;
....
public SlaveClass (MasterClass publisher) //inject publisher service
{
publisher.ChangeHappenedEvent += ChangeHappened;
}
But this seems to be like an un-necessary coupling between the Slave and the Master, but I like the elegance of the provided build-in event notification mechanism.
So should I keep my current code, or move to the event based approach (with publisher injection)? and why?
Or if you can propose an alternative solution I might have missed, I would appreciate that as well.