设计模式---组合模式(CSDN依然没有恢复迹象......)

设计模式—组合模式(CSDN依然没有恢复迹象……)

7fef7ad965c15b3411df9b0d.jpg

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
abstract class AbstractCompany
{
protected String Name;

public AbstractCompany(string name)
{
this.Name = name;
}

public abstract void Add(AbstractCompany c);

public abstract void Remove(AbstractCompany c);

public abstract void Show(int len);

public abstract void DoJob();
}

class RealCompany : AbstractCompany
{
private IList<AbstractCompany> Son = new List<AbstractCompany>();

public RealCompany(string name) : base(name)
{
}

public override void Add(AbstractCompany c)
{
Son.Add(c);
}

public override void DoJob()
{
Console.WriteLine(Name + "公司正常运转");
foreach (AbstractCompany a in Son)
{
a.DoJob();
}
}

public override void Remove(AbstractCompany c)
{
Son.Remove(c);
}

public override void Show(int len)
{
Console.WriteLine(new String('-', len) + Name);
foreach (AbstractCompany a in Son)
{
a.Show(len + 1);
}
}
}

class HR : AbstractCompany
{
public HR(string name) : base(name)
{
}

public override void Add(AbstractCompany c)
{
}

public override void DoJob()
{
Console.WriteLine(Name + "人事部正常运转");
}

public override void Remove(AbstractCompany c)
{
}

public override void Show(int len)
{
Console.WriteLine(new string('-', len) + Name);
}
}

class Client
{
public static void Main()
{
AbstractCompany root = new RealCompany("总公司");
root.Add(new HR("总公司人事部"));

RealCompany r = new RealCompany("分公司");
r.Add(new HR("分公司人事部"));

root.Add(r);

root.Show(1);
root.DoJob();

Console.Read();
}
}
}