例子
透明组合
- 部门 -》公司,部门,部门小组,员工
public abstract class AbsComponent
{
protected string Name { get; }
protected NodeType NodeType { get; }
protected AbsComponent(string name, NodeType nodeType)
{
Name = name;
NodeType = nodeType;
}
public abstract void Add(AbsComponent productComponent);
public abstract void Remove(AbsComponent productComponent);
public abstract void Display(int depth);
}
public abstract class Composite : AbsComponent
{
protected List<AbsComponent> Components { get; }
public Composite(string name, NodeType nodeType) : base(name, nodeType)
{
Components = new List<AbsComponent>();
}
public override void Add(AbsComponent productComponent)
{
Components.Add(productComponent);
}
public override void Remove(AbsComponent productComponent)
{
Components.Remove(productComponent);
}
public override void Display(int depth)
{
for (int i = 0; i < depth; i++)
{
Console.Write("----");
}
Console.WriteLine(Name);
foreach (var component in Components)
{
component.Display(depth + 1);
}
}
}
public class DepartmentComposite : Composite
{
public DepartmentComposite(string name) : base(name, NodeType.Department)
{
}
}
public class GroupComposite : Composite
{
public GroupComposite(string name) : base(name, NodeType.Group)
{
}
}
public class RootComposite : Composite
{
public RootComposite(string name) : base(name, NodeType.Root)
{
}
}
public enum NodeType
{
Root = 0,
Department = 1,
Group = 2,
Person = 3
}
public class Person : AbsComponent
{
public Person(string name) : base(name,NodeType.Person)
{
}
public override void Add(AbsComponent productComponent)
{
throw new NotImplementedException();
}
public override void Remove(AbsComponent productComponent)
{
throw new NotImplementedException();
}
public override void Display(int depth)
{
for (int i = 0; i < depth; i++)
{
Console.Write("----");
}
Console.WriteLine(Name);
}
}
static void Main(string[] args)
{
var root = new RootComposite("总公司");
var developmentDepartment = new DepartmentComposite("开发部");
var renshiDepartment = new DepartmentComposite("人事");
var chanpingDepartment = new DepartmentComposite("产品");
root.Add(developmentDepartment);
root.Add(renshiDepartment);
root.Add(chanpingDepartment);
var aRenshiDepartment = new GroupComposite("人事一组");
renshiDepartment.Add(aRenshiDepartment);
developmentDepartment.Add(new Person("cxl"));
developmentDepartment.Add(new Person("cxl2"));
aRenshiDepartment.Add(new Person("牛逼"));
root.Display(0);
}