#region Interface For The Composite Pattern
public interface IComponent
{
#region Properties
string Name
{
get;
set;
}
#endregion
#region Methods
void Add(IComponent component);
void Remove(IComponent component);
void Display(int depth);
#endregion
}
#endregion
#region Compoite Leaf
public class Component : IComponent
{
#region Ctor
/// <summary>
/// Consruct a new Component object with the
/// given name
/// </summary>
/// <param name="name">The given names</param>
public Component(string name)
{
Name = name;
}
#endregion
#region IComponent Members
/// <summary>
/// The name of the component
/// </summary>
public string Name
{
get; set;
}
/// <summary>
/// This method isn't implemented because a component
/// is a leaf of the composite
/// </summary>
public void Add(IComponent component)
{
throw new NotImplementedException("Can't add component");
}
/// <summary>
/// This method isn't implemented because a component
/// is a leaf of the composite
/// </summary>
public void Remove(IComponent component)
{
throw new NotImplementedException("Can't remove component");
}
/// <summary>
/// Displays the depth of the component
/// </summary>
/// <param name="depth">The depth of the component</param>
public void Display(int depth)
{
Console.WriteLine(
string.Format("The {0} is in depth {1}", Name, depth));
}
#endregion
}
#endregion
#region Composite
public class Composite : IComponent
{
#region Members
private List<IComponent> children;
#endregion
#region Ctor
/// <summary>
/// Construct a new Composite object with the give name
/// </summary>
/// <param name="name">The given name</param>
public Composite(string name)
{
Name = name;
children = new List<IComponent>();
}
#endregion
#region IComponent Members
/// <summary>
/// The name of the composite
/// </summary>
public string Name
{
get; set;
}
/// <summary>
/// Adds the given component to the composite
/// </summary>
/// <param name="component">The component to add</param>
public void Add(IComponent component)
{
children.Add(component);
}
/// <summary>
/// Removes the given component form the composite
/// </summary>
/// <param name="component">The component to remove</param>
public void Remove(IComponent component)
{
children.Remove(component);
}
/// <summary>
/// Display the depth of the composite and it's
/// children
/// </summary>
/// <param name="depth">The given depth to display</param>
public void Display(int depth)
{
Console.WriteLine(
string.Format("The {0} is in depth {1}", Name, depth));
foreach (IComponent component in children)
{
component.Display(depth + 1);
}
}
#endregion
}
#endregion