# 组合模式
属于结构型模式,它创建了一个树形结构。
将对象组合成树形结构以表示 "部分 - 整体" 的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
应用场景:
- 想表示对象的部分 - 整体层次结构(树形结构)。
- 希望用户忽略组合对象与单个对象的不同,用户将统一地使用组合结构中的所有对象。
# 类图
# 代码
# 组件抽象类及其子类
namespace StructuralPattern_CompositePattern | |
{ | |
/// <summary> | |
/// 组件 | |
/// </summary> | |
public abstract class Component | |
{ | |
public string Name; | |
/// <summary> | |
/// 储存子节点 | |
/// </summary> | |
private List<Component> Components; | |
public Component(string name) | |
{ | |
Name = name; | |
Components = new List<Component>(); | |
} | |
/// <summary> | |
/// 添加 | |
/// </summary> | |
/// <param name="component"></param> | |
public virtual void Add(Component component) | |
{ | |
Components.Add(component); | |
} | |
/// <summary> | |
/// 移除 | |
/// </summary> | |
/// <param name="component"></param> | |
public virtual void Remove(Component component) | |
{ | |
Components.Remove(component); | |
} | |
public virtual void Show(int depth) | |
{ | |
Console.WriteLine(new string('-', depth) + Name); | |
foreach (Component component in Components) | |
{ | |
component.Show(depth + 3); | |
} | |
} | |
} | |
} |
namespace StructuralPattern_CompositePattern | |
{ | |
public class Composite : Component | |
{ | |
public Composite(string name) : base(name) { } | |
} | |
} |
# 测试
namespace StructuralPattern_CompositePattern | |
{ | |
public class Program | |
{ | |
private static void Main() | |
{ | |
Component composite_0 = new Composite("Composite_0"); | |
composite_0.Add(new Composite("Composite_1")); | |
composite_0.Add(new Composite("Composite_2")); | |
Component composite_3 = new Composite("Composite_3"); | |
composite_3.Add(new Composite("Composite_4")); | |
composite_3.Add(new Composite("Composite_5")); | |
Component composite_6 = new Composite("Composite_6"); | |
composite_6.Add(new Composite("Composite_7")); | |
composite_6.Add(new Composite("Composite_8")); | |
composite_0.Add(composite_3); | |
composite_3.Add(composite_6); | |
composite_0.Add(new Composite("Composite_9")); | |
composite_0.Show(1); | |
} | |
} | |
} |
运行结果:
-Composite_0
----Composite_1
----Composite_2
----Composite_3
-------Composite_4
-------Composite_5
-------Composite_6
----------Composite_7
----------Composite_8
----Composite_9