1 public class CompositePattern
2 {
3 public interface IComponent<T>
4 {
5 string Name { get; set; }
6 void Add( IComponent<T> component );
7 void Remove( IComponent<T> component );
8 void Display( int depth );
9 }
10
11 public class Composite<T> : IComponent<T>
12 {
13 public string Name { get; set; }
14 private List<IComponent<T>> _list;
15
16 public Composite( string name )
17 {
18 Name = name;
19 _list = new List<IComponent<T>>();
20 }
21
22 public void Add( IComponent<T> component )
23 {
24 _list.Add( component );
25 }
26
27 public void Remove( IComponent<T> component )
28 {
29 _list.Remove( component );
30 }
31
32 public void Display( int depth )
33 {
34 Console.WriteLine( new String( '-', depth ) + Name + " | Length : " + _list.Count );
35 foreach ( IComponent<T> component in _list )
36 {
37 component.Display( depth + 1 );
38 }
39 }
40 }
41
42 public class Component<T> : IComponent<T>
43 {
44 public string Name { get; set; }
45
46 public Component( string name )
47 {
48 Name = name;
49 }
50
51 //A component can not add on to itself, So show a freindly message
52 public void Add( IComponent<T> component )
53 {
54 throw new System.NotSupportedException( "Can't add an item" );
55 }
56
57 //A component can not delete from itself, So show a freindly message
58 public void Remove( IComponent<T> component )
59 {
60 throw new System.NotSupportedException( "Can't remvove an item" );
61 }
62
63 public void Display( int depth )
64 {
65 Console.WriteLine( new String( '-', depth ) + Name );
66 }
67 }
68
69 //Person stub
70 public class Person { }
71
72 private static void Main()
73 {
74 IComponent<Person> group = new Composite<Person>( "Group" );
75 group.Add( new Component<Person>( "Person1" ) );
76 group.Add( new Component<Person>( "Person2" ) );
77
78 IComponent<Person> subgroup = new Composite<Person>( "SubGroup" );
79 subgroup.Add( new Component<Person>( "Person2" ) );
80 subgroup.Add( new Component<Person>( "Person3" ) );
81
82 group.Add( subgroup );
83
84 group.Display( 0 );
85
86 //Output :
87 //Group | Length : 3
88 //-Person1
89 //-Person2
90 //-SubGroup | Length : 2
91 //--Person2
92 //--Person3
93
94 Console.ReadLine();
95 }
96 }