0%

设计模式-组合模式

用于把一组相似的对象当作一个单一的对象

组合模式

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
//Component
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);
}
//Leaf 叶节点
class Leaf : Component
{
public Leaf(string name) : base(name)
{}
public override void Add(Component c)
{
Console.WriteLine("Can not add to a leaf");
}
public override void Remove(Component c)
{
Console.WriteLine("Can not remove from a leaf");
}
public override void Display(int depth)
{
Console.WriteLine(new String('-', depth) + "name");
}
}
//Composite 枝节点 用于存储子部件
class Composite : Component
{
private List<Component> children = new List<Component>();
public Composite(string name) : base(name)
{}
public override void Add(Component c)
{
children.Add(c);
}
public override void Remove(Component c)
{
children.Remove(c);
}
public override void Display(int depth)
{
Console.WriteLine(new String('-', depth) + "name");
children.Foreach(c.Display(depth + 2);)
}
}
//Client
Composite root = new Composite("root");
root.Add(new Leaf("Leaf A"));
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);