组合模式
定义:
组合模式,将对象组合成树形结构以表示“部分-整体”的层次结构,组合模式使得用户对单个对象和组合对象的使用具有一致性
构成:
1.Component 是组合中的对象声明接口,在适当的情况下,实现所有类共有接口的默认行为。声明一个接口用于访问和管理Component子部件。
2.Leaf 在组合中表示叶子结点对象,叶子结点没有子结点。
3.Composite 定义有枝节点行为,用来存储子部件,在Component接口中实现与子部件有关操作,如增加(add)和删除(remove)等。
结构图:
举例:公司管理系统
结构图:
代码:
公司类:
//公司类 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 component in children) { component.Display(depth + 2); } } public override void LineOfDuty() { foreach (Company component in children) { component.LineOfDuty(); } } }人力资源部和财务部类:
//人力资源部和财务部类 class HRDepartment : Company { public HRDepartment(string name) : base(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); } } class FinanceDepartment : Company { public FinanceDepartment(string name) : base(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); } } }
在我们生活和学习中,有很多地方用到组合模式,如自定义控件等,当你发现需求中是体现部分和整体层次的结构时,以及你 希望用户可以忽略组合对象与单个对象的不同,统一地使用组合结构中的所有对象时,就应该考虑用组合模式了。