Structure Chart:
Abstract objects:
Copy Code code as follows:
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 depth);
}
With No child nodes:
Copy Code code as follows:
Class Leaf:component
{
Public Leaf (string name)
: Base (name)
{ }
public override void Add (Component c)
{
throw new NotImplementedException ();
Console.WriteLine ("Cannot add to a Leaf");
}
public override void Remove (Component c)
{
throw new NotImplementedException ();
Console.WriteLine ("Cannot remove to a Leaf");
}
public override void Display (int depth)
{
throw new NotImplementedException ();
Console.WriteLine (New String ('-', depth) + name);
}
}
You can have child nodes:
Copy Code code as follows:
Class Composite:component
{
Private list<component> children = new list<component> ();
Public composite (string name)
: Base (name)
{ }
public override void Add (Component c)
{
throw new NotImplementedException ();
Children. ADD (c);
}
public override void Remove (Component c)
{
throw new NotImplementedException ();
Children. Remove (c);
}
public override void Display (int depth)
{
throw new NotImplementedException ();
Console.WriteLine (New String ('-', depth) + name);
foreach (Component Component in children)
{
Component. Display (depth + 2);
}
}
}
Main function Call:
Copy Code code as follows:
Class Program
{
static void Main (string[] args)
{
Composite root = new Composite ("root");
Root. ADD (The New Leaf ("Leaf A"));
Root. ADD (The New Leaf ("Leaf B"));
Composite comp = new Composite ("Composite X");
Comp. ADD (The New Leaf ("Leaf XA"));
Comp. ADD (New Leaf ("Leaf XB"));
Root. ADD (comp);
Composite COMP2 = new Composite ("Composite X");
Comp2. ADD (The New Leaf ("Leaf Xya"));
Comp2. ADD (The New Leaf ("Leaf xyb"));
Comp. ADD (COMP2);
Root. Display (1);
Console.readkey ();
}
}