将对象组合成树形结构以表示部分整体的层次结构,组合模式使得用户对单个对象和组合对象的使用具有一致性。
公司管理系统
abstract class company {
protected string name;
public Company(string name) {
this.name = name;
}
public abstract void Add(Company c);
public abstract void Remove(Company c);
public abstract void Display(int depth);
public abstract void LineOfDuty();
}
class ConcreteCompany : Company {
private List<Company> children = new List<Company>();
public ConcreteCompany(string name) : base(name){}
public override void Add(Company c) {
children.Add(c);
}
public override void Remove(Company c){
children.Remove(c);
}
public override void Display(int depth) {
Console.WriteLine(new String('-',depth) + name);
foreach(Company componet in children) {
componet.Display(depth +2);
}
}
public override void LineOfDuty() {
foreach(Company c in children) {
componet.LineOfDuty();
}
}
}
// 人力资源部
class HRDepartment : Company {
public HrDepartment(string name){}
public override void Add(Company c){}
public override void Remove(Company c){}
public override void Display(int depth) {
Console.WriteLine(new String('-',depth) + name);
}
public override void LineOfDuty() {
Console.WriteLine("{0} 员工招聘培训管理",name);
}
}
//..
// 客户端
static void Main(string[] args){
ConcreteCompany root = new ConcreteCompany("北京总公司");
root.Add(new HRDepartment("总公司人力资源部"));
ConcreteCompnay comp = new ConcreteCompany("上海华东分公司");
comp.Add(new HRDepartment("华东分公司人力资源部"));
root.Add(comp);
//以下类似
//组成总公司是由各个分公司以及分公司下面的部门组成的
}