Created
August 10, 2016 16:12
-
-
Save mat-mcloughlin/a25c5866800673085738c93e71d6f0da to your computer and use it in GitHub Desktop.
Basic implementation of a command register
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((T)cmd); | |
}; | |
Handlers.Add(typeof(T), action); | |
} | |
} | |
class Dispatcher | |
{ | |
CommandRegister register; | |
public Dispatcher(CommandRegister register) | |
{ | |
this.register = register; | |
} | |
public void Send<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