Structure:
Abstract object:
Copy codeThe Code is 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 );
}
For non-subnodes:Copy codeThe Code is 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 );
}
}
There can be subnodes:Copy codeThe Code is 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 codeThe Code is as follows: class Program
{
Static void Main (string [] args)
{
Composite root = new Composite ("root ");
Root. Add (new Leaf ("Leaf "));
Root. Add (new Leaf ("Leaf B "));
Composite comp = new Composite ("Composite X ");
Comp. Add (new Leaf ("Leaf XA "));
Comp. Add (new Leaf ("Leaf XB "));
Root. Add (comp );
Composite comp2 = new Composite ("Composite X ");
Comp2.Add (new Leaf ("Leaf XYA "));
Comp2.Add (new Leaf ("Leaf XYB "));
Comp. Add (comp2 );
Root. Display (1 );
Console. ReadKey ();
}
}