My event dispatcher class loosely couples instances of other classes by implementing sort of signals-slots design pattern.
Only one unique event dispatcher is supposed to exist in an application.
Since my Dispatcher class – which does all the work – inherits from Dictionary<TKey, TValue>, it cannot be declared static.
To overcome this constraint, I implemented a main static wrapper class EVD with a private property evd which provides the Dispatcher singleton, along with the public static methods Subscribe, UnSubscribe, and Dispatch, which wrap the singleton's corresponding methods:
namespace EventDispatcher
{
public static class EVD
{
static Dispatcher evd { get { return Singleton<Dispatcher>.Instance; } }
public static void Subscribe(string name, EvtHandler handler)
{
evd.Subscribe(name, handler);
}
public static void UnSubscribe(string name, EvtHandler handler = null)
{
evd.UnSubscribe(name, handler);
}
public static void Dispatch(string name, object sender, EvtArgs e = null)
{
evd.Dispatch(name, sender, e);
}
}
class Dispatcher : Dictionary<string, Event> { /* main event dispatcher */ }
static class Singleton<T> where T : /* generic singleton creation */
}
So here is my question:
Does it really make sense to create a singleton instance in a static class? AFAIK a static class is unique anyway. So maybe it would be best practice not to create the singleton and declare the evd property just like so:
static Dispatcher evd = new Dispatcher();
What about lazy intantiation and thread safety in that case? At least the generic singleton class uses Lazy<T> and is said to be thread safe.
Or should I better declare the property like so:
static Dispatcher _evd;
static Dispatcher evd
{
get { return _evd ?? (_evd = new Dispatcher()); }
}
I'm afraid I don't completely understand all that lazy instatantiation and thread safety stuff...
Thanks for any help, Don P
Singleton<Dispatcher>, but isn't it unnecessary overhead?