组合模式【大话设计模式DEMO】
组合模式:将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
整体与部分可以被一致对待。(看上去也有递归的感觉)
类设计图:
DEMO代码:
代码
class RunCompositePattern
{
static void Main(string[] args)
{
Composite root = new Composite("root");
root.Add(new Leaf("A"));
root.Add(new Leaf("B"));
Composite comp = new Composite("Compostie X");
comp.Add(new Leaf("Leaf XA"));
comp.Add(new Leaf("Leaf XB"));
root.Add(comp);
Composite comp2 = new Composite("Compostie XY");
comp2.Add(new Leaf("Leaf XYA"));
comp2.Add(new Leaf("Leaf XYB"));
comp.Add(comp2);
root.Add(new Leaf("C"));
Leaf leaf = new Leaf("D");
root.Add(leaf);
root.Remove(leaf);
root.Display(1);
Console.ReadKey();
}
}
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);
}
class Leaf : Component
{
public Leaf(string name)
: base(name)
{
}
public override void Add(Component c)
{
Console.WriteLine("不能为叶子节点添加子元素");
}
public override void Remove(Component c)
{
Console.WriteLine("不能从叶子节点删除子元素");
}
public override void Display(int depth)
{
Console.WriteLine(new String('-', depth) + Name);
}
}
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);
foreach (Component item in children)
{
item.Display(depth + 2);
}
}
}
运行结果: