-
-
Save Zshazz/90dfcd952e1cfd933bc1 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; | |
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