C # Combination Mode

Source: Internet
Author: User

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 ();
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.