学习笔录——设计模式
组合模式
组合模式模式
简介
将对象组合成树形结构以表示'部分_整体'的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性
代码示例
public abstract class ComponentBasae
{
public abstract void Add(ComponentBasae component);
public abstract void Remove(ComponentBasae component);
public abstract void Display(int depth);
}
/// <summary>
/// 枝节点
/// </summary>
public class Composite : ComponentBasae
{
private List<ComponentBasae> children = new List<ComponentBasae>();
public override void Add(ComponentBasae component)
{
this.children.Add(component);
}
public override void Remove(ComponentBasae component)
{
this.children.Remove(component);
}
public override void Display(int depth)
{
System.Console.WriteLine($"{depth}");
this.children.ForEach(item=>
{
item.Display(depth);
});
}
}
/// <summary>
/// 叶节点
/// </summary>
public class Leaf : ComponentBasae
{
public override void Add(ComponentBasae component)
{
System.Console.WriteLine("叶不能添加叶");
}
public override void Remove(ComponentBasae component)
{
System.Console.WriteLine("不能从叶删除");
}
public override void Display(int depth)
{
System.Console.WriteLine($"{depth}");
}
}
static void Main(string[] args)
{
Composite root = new Composite();
root.Add(new Leaf());
Composite root1 = new Composite();
root1.Add(new Leaf());
root.Add(root1);
root.Display(1);
}