Skip to content

Instantly share code, notes, and snippets.

@j-didi
Created November 14, 2020 20:44
Show Gist options
  • Save j-didi/15443dec9f95c07379f632875755de77 to your computer and use it in GitHub Desktop.
Save j-didi/15443dec9f95c07379f632875755de77 to your computer and use it in GitHub Desktop.
Mediator C# Implementation
// Colleague only exposes Notify method
// SetMediator and HandleNotification are private and protected to simplify client interface
// Not public methods are invoked using reflection.
public abstract class Colleague
{
private IMediator _mediator;
protected void SetMediator(IMediator mediator)
{
_mediator = mediator;
}
protected abstract void HandleNotification(string message);
public void Notify(string message)
{
_mediator.Notify(message, this);
}
}
public class Colleague1 : Colleague
{
protected override void HandleNotification(string message)
{
Console.WriteLine($"{nameof(Colleague1)}: {message}");
}
}
public class Colleague2 : Colleague
{
protected override void HandleNotification(string message)
{
Console.WriteLine($"{nameof(Colleague2)}: {message}");
}
}
public interface IMediator
{
void Notify(string message, Colleague colleague);
}
public class Mediator: IMediator
{
private readonly List<Colleague> _colleagues = new List<Colleague>();
public Colleague CreateColleague<T>() where T : Colleague, new()
{
var colleague = new T();
CallColleagueNoPublicMethod(colleague, "SetMediator", this);
_colleagues.Add(colleague);
return colleague;
}
public void Notify(string message, Colleague colleague)
{
var instance = _colleagues.FirstOrDefault(e => e == colleague);
CallColleagueNoPublicMethod(instance, "HandleNotification", message);
}
private static void CallColleagueNoPublicMethod(Colleague instance, string methodName, object parameter)
{
var method = instance.GetType().GetMethod(
methodName,
BindingFlags.NonPublic |
BindingFlags.Instance
);
method!.Invoke(instance, new[] { parameter });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment