Created
February 13, 2012 10:34
-
-
Save follesoe/1815856 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var handlers = new MyHandlerList(); | |
handlers.Add(new ConcreteHandler()); | |
var myHandler = handlers.Get<Message>(); | |
} | |
private class MyHandlerList | |
{ | |
private readonly Dictionary<Type, object> _handlers = new Dictionary<Type, object>(); | |
public void Add<T>(IHandler<T> handler) where T : IMessage | |
{ | |
_handlers.Add(typeof(T), handler); | |
} | |
public IHandler<T> Get<T>() where T : IMessage | |
{ | |
if (_handlers.ContainsKey(typeof(T))) | |
return _handlers[typeof(T)] as IHandler<T>; | |
throw new Exception("Not found"); | |
} | |
} | |
private interface IHandler<in TMessage> | |
where TMessage : IMessage | |
{ | |
void Handle(TMessage message); | |
} | |
private interface IMessage | |
{ | |
} | |
private class Message : IMessage | |
{ | |
} | |
class ConcreteHandler : IHandler<Message> | |
{ | |
private IMessage Message { get; set; } | |
public void Handle(Message message) | |
{ | |
Message = message; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment