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("Leaf cannot add");
}
public override void Remove(Component c)
{
Console.WriteLine("Leaf cannot remove");
}
public override void Display(int depth)
{
Console.WriteLine(new string('-', depth) + name);
}
}
class Composite : Component
{
public Composite(string name) : base(name) { }
IList<Component> children = new List<Component>();
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 c in children)
{
c.Display(depth + 2);
}
}
}
// 业务代码:
Composite root = new Composite("高新兴");
Leaf gc = new Leaf("财务部");
Leaf gi = new Leaf("IT 部");
Leaf ghr = new Leaf("人力");
root.Add(gc);
root.Add(gi);
root.Add(ghr);
Composite pa = new Composite("平安事业部");
Leaf pahr = new Leaf("人力");
Composite payf = new Composite("研发");
Leaf jg = new Leaf("交通");
payf.Add(jg);
pa.Add(pahr);
pa.Add(payf);
root.Add(pa);
root.Display(1);
- Y 公司
---财务部
---IT 部
---人力
--- X 事业部
-----人力
-----研发
-------交通
组合模式定义了基本对象和组合对象,基本对象可以被组合到更复杂的组合对象,而组合对象又可以被组合,不断递归;
可以在各个基本对象中定义内部对继承的抽象类的实现,而用户并不需要知道是处理一个基本对象还是组合对象,因此用不着写一些判断语句。