Combination Mode: Combine objects into a tree structure to represent the "part-whole" hierarchy. The combination mode ensures consistency between the use of a single object and a composite object.
The whole and part can be treated in the same way. (It also seems like recursion)
Class design diagram:
DEMO code:
Code
Class runcompositepattern
{
Static void main (string [] ARGs)
{
Composite root = new composite ("root ");
Root. Add (new leaf (""));
Root. Add (new leaf ("B "));
Composite comp = new composite ("compostie X ");
Comp. Add (new leaf ("leaf xa "));
Comp. Add (new leaf ("leaf XB "));
Root. Add (COMP );
Composite comp2 = new composite ("compostie XY ");
Comp2.add (new leaf ("leaf xya "));
Comp2.add (new leaf ("leaf xyb "));
Comp. Add (comp2 );
Root. Add (new leaf ("C "));
Leaf leaf = new leaf ("D ");
Root. Add (leaf );
Root. Remove (leaf );
Root. Display (1 );
Console. readkey ();
}
}
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 );
}
Class leaf: Component
{
Public leaf (string name)
: Base (name)
{
}
Public override void add (component C)
{
Console. writeline ("child elements cannot be added to leaf nodes ");
}
Public override void remove (component C)
{
Console. writeline ("child elements cannot be deleted from leaf nodes ");
}
Public override void display (INT depth)
{
Console. writeline (new string ('-', depth) + name );
}
}
Class Composite: Component
{
Private list <component> Children = new list <component> ();
Public composite (string name)
: Base (name)
{}
Public override void add (component C)
{
Children. Add (C );
}
Public override void remove (component C)
{
Children. Remove (C );
}
Public override void display (INT depth)
{
Console. writeline (new string ('-', depth) + name );
Foreach (Component item in children)
{
Item. Display (depth + 2 );
}
}
}
Running result: