Skip to content

Instantly share code, notes, and snippets.

@justinmchase
Last active August 29, 2015 14:11
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 justinmchase/7f429c7f74de9003f2f4 to your computer and use it in GitHub Desktop.
Save justinmchase/7f429c7f74de9003f2f4 to your computer and use it in GitHub Desktop.
Simple Composition Design
interface IObject
{
string Name { get; }
IObject Parent { get; }
void Add(string name, IComponent component);
void Add(IObject child);
void Remove(IObject child);
IComponent GetComponent(string name);
IEnumerable<IObject> GetChildren();
void SendMessage(string message, params object[] parameters);
}
interface IComponent
{
IObject Object { get; }
}
// A naieve implementation of SendMessage
public void SendMessage(string message, params object[] parameters)
{
var types = parameters.Select(a => a == null ? typeof(object) : a.GetType()).ToArray();
foreach (var component in this.components.Values)
{
var method = component.GetType().GetMethod(message, types);
if (method != null)
{
// Call methods on the component via reflection
method.Invoke(component, parameters);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment