Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple composition pattern
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
var root = new Node()
{
new Node("child1"),
new Node("child2")
{
new LogComponent()
}
};
root.Send("Log", "success!");
Console.ReadKey(true);
}
}
class LogComponent : Component
{
public void Log(string message)
{
Console.WriteLine(message);
}
}
class Component
{
public Node @this;
public void Send(string message, params object [] args)
{
var member = this.GetType().GetMethod(message);
if (member != null)
{
member.Invoke(this, args);
}
}
}
class Node :
IEnumerable<Node>,
IEnumerable<Component>
{
private List<Component> components = new List<Component>();
private List<Node> children = new List<Node>();
private Node parent;
private string name;
public Node(string name = null)
{
this.name = name;
}
public void Add(Component component)
{
component.@this = this;
this.components.Add(component);
}
public void Add(Node child)
{
if (child.parent != null)
{
child.parent.children.Remove(child);
child.parent = null;
}
child.parent = this;
this.children.Add(child);
}
public void Send(string message, params object[] args)
{
foreach(var c in this.components)
{
c.Send(message, args);
}
foreach(var child in this.children)
{
child.Send(message, args);
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.children.Cast<object>().Concat(this.components.Cast<object>()).GetEnumerator();
}
IEnumerator<Node> IEnumerable<Node>.GetEnumerator()
{
return this.children.GetEnumerator();
}
IEnumerator<Component> IEnumerable<Component>.GetEnumerator()
{
return this.components.GetEnumerator();
}
}
}
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.