Skip to content

Instantly share code, notes, and snippets.

@Zshazz

Zshazz/Program.cs Secret

Created May 28, 2015
Embed
What would you like to do?
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
You can’t perform that action at this time.