Skip to content

Instantly share code, notes, and snippets.

@Zshazz
Created May 28, 2015 23:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zshazz/90dfcd952e1cfd933bc1 to your computer and use it in GitHub Desktop.
Save Zshazz/90dfcd952e1cfd933bc1 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
namespace SimpleCompositionPattern
{
class Program
{
static void Main()
{
var singleton = new BusOrMediatorOrWhatever(new[]
{
new LogHandler(),
});
singleton.Send(new LogCmd("success!"));
}
class LogCmd
{
public LogCmd(string text) { Text = text; }
public string Text { get; private set; }
}
class LogHandler : IHandler<LogCmd>
{
public void Handle(LogCmd message)
{
Console.WriteLine(message.Text);
}
}
//Implementation:
interface IHandler<in TCommand>
{
void Handle(TCommand message);
}
class BusOrMediatorOrWhatever
{
private readonly IReadOnlyCollection<object> _components;
public BusOrMediatorOrWhatever(IReadOnlyCollection<object> components)
{
_components = components;
}
public void Send<TCommand>(TCommand message)
{
foreach (var component in _components.OfType<IHandler<TCommand>>()) // typically this would be .Take(1) since usually commands only have 1 handler, but either way...
component.Handle(message);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment