Question

I realise there are several posts on here regarding my question, but none seem to offer a solution particular to my case.

I have a short static class, looking like this:

public static class NotificationCenter
{
    private static readonly Dictionary<Type, object> Notifiers = new Dictionary<Type, object>();

    public static INotifier<T> NotifierForType<T>()
    {
        object notifier = null;
        return Notifiers.TryGetValue(typeof(T), out notifier) 
            ? (INotifier<T>)notifier 
            : null;
    }

    public static void RegisterNotifier<T>(INotifier<T> notifier)
    {
        Notifiers[typeof(T)] = notifier;
    }
}

The above works fine, but I'm not keen on storing the INotifiers in an IDictionary<Type, object> - specifically, I'm not keen on the object part, because it makes the collection non-type-safe.

I've read many similar posts that recommend deriving INotifier<T> from a base interface called INotifier, but I don't believe this is suitable in my instance, because the INotifier<T> interface looks like this:

interface INotifier<T>
{
    void Notify(T notification);
}

If I were to derive from a base class, the base class would not be able to implement the Notify method (unless it were implemented with the signature void Notify(object notification) but then we're back to square one), and that is what I want the client of the INotifier<T> class to be able to invoke.

Was it helpful?

Solution

Do you need to enumerate all notifiers? If not the solution can be pretty simple:

namespace NotifierTest
{
    interface INotifier<T>
    {
        void Notify(T notification);
    }

    class Notifier<T> : INotifier<T>
    {
        public void Notify(T notification) 
        {
            Debug.Print("Notify: " + notification);
        }
    }

    static class NotificationCenter<T>
    {
        public static INotifier<T> notifier;
    }

    class Program
    {
        static void Main(string[] args)
        {
            NotificationCenter<int>.notifier = new Notifier<int>();
            NotificationCenter<int>.notifier.Notify(5);
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top