Composite Pattern
[Download cs c#]Definition
Compose
objects into tree structures to represent part-whole hierarchies. Composite
lets clients treat individual objects and compositions of objects uniformly.
//Component class
abstract class Component
{
protected string
name;
public
Component(string name)
{
this.name = name;
}
public abstract void Add(Component
c);
public abstract void Remove(Component
c);
public abstract void Display(int
Dept);
}
//Composite Class
class Composite : Component
{
private List<Component> _com = new
List<Component>();
public Composite(string
name):base(name)
{
}
public override void Add(Component
c)
{
_com.Add(c);
}
public override void Remove(Component
c)
{
_com.Remove(c);
}
public override void Display(int
Dept)
{
Console.WriteLine(new
String('-',Dept)+name);
foreach (Component
component in _com)
{
component.Display(Dept + 2);
}
}
}
//Leaf Class
class Leaf : Component
{
public Leaf(string
name):base(name)
{
}
public override void Add(Component c)
{
Console.WriteLine("Can not add to a leaf");
}
public override void Remove(Component
c)
{
Console.WriteLine("Can not remove from a leaf");
}
public override void Display(int
Dept)
{
Console.WriteLine(new String('-', Dept) + name);
}
}
//---Composite Calling...
Composite root = new
Composite("root");
root.Add(new Leaf("Leaf A"));
root.Add(new Leaf("Leaf B"));
Composite comp = new
Composite("Composite
X");
comp.Add(new Leaf("Leaf XA"));
comp.Add(new Leaf("Leaf XAB"));
root.Add(comp);
root.Add(new Leaf("Leaf C"));
// Add and remove a leaf
Leaf leaf = new Leaf("Leaf
D");
root.Add(leaf);
root.Remove(leaf);
// Recursively display tree
root.Display(1);