Composite: Composite combines objects into a tree structure to represent the 'partial-uniyun' hierarchy. The combination mode ensures consistency between the use of a single object and a composite object.
Combined mode code Using System;
Using System. Collections. Generic;
Using System. Text;
Namespace Composite
{
Class Program
{
Static void Main (string [] args)
{
ConcreteCompany root = new ConcreteCompany ("Beijing Head Office ");
Root. Add (new HRDepartment ("Head Office Human Resources Department "));
ConcreteCompany comp = new ConcreteCompany ("Shanghai East China Branch ");
Comp. Add (new HRDepartment ("Shanghai East China Branch Human Resources Department "));
Root. Add (comp );
Console. WriteLine ("structure chart :");
Root. Display (1 );
Console. WriteLine ("Responsibility :");
Root. LineOfDuty ();
Console. ReadLine ();
}
}
// Define abstract company classes
Abstract class Company
{
Private string _ name;
Protected string Name
{
Get {return _ name ;}
Set {_ name = value ;}
}
Public Company (string name)
{
This. _ name = name;
}
Public abstract void Add (Company c );
Public abstract void Remove (Company c );
Public abstract void Display (int depth); // Display
Public abstract void LineOfDuty ();
}
Class ConcreteCompany: Company
{
Private List <Company> children = new List <Company> ();
Public ConcreteCompany (string name)
: Base (name)
{
}
Public override void Add (Company c)
{
Children. Add (c );
}
Public override void Remove (Company c)
{
Children. Remove (c );
}
Public override void Display (int depth)
{
Console. WriteLine (new string ('-', depth) + Name );
Foreach (Company component in children)
{
Component. Display (depth + 2 );
}
}
Public override void LineOfDuty ()
{
Foreach (Company component in children)
{
Component. LineOfDuty ();
}
}
}
Class HRDepartment: Company
{
Public HRDepartment (string name)
: Base (name)
{}
Public override void Add (Company c)
{
Throw new Exception ("The method or operation is not implemented .");
}
Public override void Remove (Company c)
{
Throw new Exception ("The method or operation is not implemented .");
}
Public override void Display (int depth)
{
Console. WriteLine (new string ('-', depth) + Name );
}
Public override void LineOfDuty ()
{
Console. WriteLine ("{0} Employee Training Management", Name );
}
}
}