C # combination Mode _c# Tutorial

Source: Internet
Author: User
Tags abstract
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 ();
}
}

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.