Last active
August 29, 2015 14:11
-
-
Save justinmchase/7f429c7f74de9003f2f4 to your computer and use it in GitHub Desktop.
Simple Composition Design
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
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; } | |
} |
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
// 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