部分和整体的关系,允许客户以统一的方式来访问对象;
1.Component
-提供统一管理Childen的接,Add/Remove
-统一的操作接口Operation
public abstract class Component
{
protected string _name;
public Component(string name)
{
_name = name;
}
public abstract void Add(Component c);
public abstract void Remove(Component c);
public abstract void Display(int depth);
}
2.Composite:实现Component的接口
-Add/Remove
-包含存储Childen的对象
public class Root : Component
{
private List<Component> _children = new List<Component>();
public Root(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 (var component1 in _children)
{
component1.Display(depth+2);
}
}
}
3.Leaf:实现Component的接口
public class Leaf : Component
{
public Leaf(string name):base(name)
{
}
public override void Add(Component c)
{
throw new NotImplementedException();
}
public override void Remove(Component c)
{
throw new NotImplementedException();
}
public override void Display(int depth)
{
Console.WriteLine(new string('-', depth) + _name);
}
}
4.Client通过统一的接口调用Component
public class Client2
{
void Call()
{
Component root = new Root("root");
root.Add(new Leaf("leaf A"));
root.Add(new Leaf("leaf B"));
Component comp = new Root("Composite X");
comp.Add(new Leaf("Leaf XA"));
comp.Add(new Leaf("Leaf XB"));
root.Add(comp);
root.Add(new Leaf("Leaf C"));
root.Display(1);
}
}