1、软件体系结构Beijing Jiaotong UniversityZhenyan Ji结构型模式-组合模式组合模式目的将对象组织成树结构以表示“部分整体”的层次结构 。组合模式让client程序以统一的方式对待单个对象和组合对象 。组合模式组合模式参与者Client使用Component接口操作层次结构中的对象。Component是Leaf节点和Composite节点的抽象,它定义了组合中对象必须实现的接口。ClientComponent组合模式Leaf是没有子节 点的对象,其实现由组件接口声明的服务。Leaf组合模式CompositeComposite存储子组件,实现Component接口定
2、义的方法。除了实现Component接口定义的方法。此外,Composite提供添加、删除以及获得组件Component的方法。例子例子public class Employee String name;float salary;Vector subordinates;/-public Employee(String _name, float _salary) name = _name;salary = _salary;subordinates = new Vector(); 例子public float getSalary() return salary;public String getN
3、ame() return name; public void add(Employee e) subordinates.addElement(e);例子public void remove(Employee e) subordinates.removeElement(e); /get a list of employees of a given supervisorpublic Enumeration elements() return subordinates.elements(); 例子:通用接口通用接口/returns a sum of salaries for the employee
4、 and his subordinatespublic float getSalaries() float sum = salary; /this ones salary/add in subordinates salariesfor(int i = 0; i subordinates.size(); i+) sum +=(Employee)subordinates.elementAt(i).getSalaries();return sum;例子:构建一棵Employee树构建一棵Employee树boss = new Employee(CEO, 200000);boss.add(market
5、VP =new Employee(Marketing VP, 100000);boss.add(prodVP =new Employee(Production VP, 100000);marketVP.add(salesMgr =new Employee(Sales Mgr, 50000);marketVP.add(advMgr =new Employee(Advt Mgr, 50000);/add salesmen reporting to Sales Managerfor (int i=0; i5; i+)salesMgr .add(new Employee(Sales +new Inte
6、ger(i).toString(), 30000.0F+(float)(Math.random()-0.5)*10000);例子advMgr.add(new Employee(Secy, 20000);prodVP.add(prodMgr =new Employee(Prod Mgr, 40000);prodVP.add(shipMgr =new Employee(Ship Mgr, 35000);/add manufacturing stafffor (int i = 0; i 4; i+)prodMgr.add( new Employee(Manuf +new Integer(i).toString(), 25000.0F+(float)(Math.random()-0.5)*5000);/add shipping clerksfor (int i = 0; i 3; i+)shipMgr.add( new Employee(ShipClrk +newInteger(i).toString(), 20000.0F+(float)(Math.random()-0.5)*5000);