Created
August 7, 2016 16:40
-
-
Save mat-mcloughlin/4b9f73221d7ab1e7bd597a9b95da1b5b to your computer and use it in GitHub Desktop.
This file contains 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
using System; | |
using System.Collections.Generic; | |
namespace ConsoleApplication | |
{ | |
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
var register = new CommandRegister(); | |
register.Register<AdmitPatient>(cmd => | |
{ | |
Console.WriteLine($"FirstName: {cmd.FirstName}"); | |
Console.WriteLine($"Surname: {cmd.Surname}"); | |
}); | |
var dispatcher = new Dispatcher(register); | |
dispatcher.Send(new AdmitPatient("Fredd", "Bloggs")); | |
} | |
class AdmitPatient | |
{ | |
public string FirstName { get; } | |
public string Surname { get; } | |
public AdmitPatient(string firstName, string surname) | |
{ | |
FirstName = firstName; | |
Surname = surname; | |
} | |
} | |
class CommandRegister | |
{ | |
public Dictionary<Type, Action<object>> Handlers { get; } | |
public CommandRegister() | |
{ | |
Handlers = new Dictionary<Type, Action<object>>(); | |
} | |
public void Register<T>(Action<T> handler) where T : class | |
{ | |
Action<object> action = cmd => | |
{ | |
handler(cmd as T); | |
}; | |
Handlers.Add(typeof(T), action); | |
} | |
} | |
class Dispatcher | |
{ | |
CommandRegister register; | |
public Dispatcher(CommandRegister register) | |
{ | |
this.register = register; | |
} | |
public void Send(object message) | |
{ | |
SendGeneric((dynamic)message); | |
} | |
void SendGeneric<T>(T command) | |
{ | |
register.Handlers[typeof(T)](command); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment