设计模式(九):组合模式
- 1. 组合模式的介绍
- 2. 组合模式的类图
- 3. 组合模式的实现
1. 组合模式的介绍
组合模式
(Composite Pattern)属于结构型模式,是用于把一组相似的对象当作一个单一的对象。
组合模式
依据树形结构来组合对象,用来表示部分以及整体层次。这种类型的设计模式它创建了对象组的树形结构。
2. 组合模式的类图
表示一个公司的组织结构,创建一个组织对象,组织对象中包含多个子组织。
3. 组合模式的实现
package blog;import java.util.List;/*** 组织结构*/
public class Organization {private String name;private List<Organization> organizations;public Organization(String name, List<Organization> organizations) {this.name = name;this.organizations = organizations;}public void add(Organization organization) {organization.add(organization);}public void remove(Organization organization) {organization.remove(organization);}public List<Organization> getOrganizations() {return organizations;}
}
package blog;import java.util.ArrayList;
import java.util.List;public class CompositeDemo {public static void main(String[] args) {Organization organization = new Organization("总裁办", new ArrayList<>());Organization sub1 = new Organization("财务部门", new ArrayList<>());Organization sub2 = new Organization("业务部门", new ArrayList<>());Organization sub3 = new Organization("研发部门", new ArrayList<>());Organization sub4 = new Organization("生产部门", new ArrayList<>());Organization sub5 = new Organization("客服部门", new ArrayList<>());Organization sub11 = new Organization("会计部门", new ArrayList<>());Organization sub12 = new Organization("出纳部门", new ArrayList<>());organization.getOrganizations().add(sub1);organization.getOrganizations().add(sub2);organization.getOrganizations().add(sub3);organization.getOrganizations().add(sub4);organization.getOrganizations().add(sub5);sub1.getOrganizations().add(sub11);sub1.getOrganizations().add(sub12);showOrganization(organization, 0);}private static void showOrganization(Organization organization, int indentation) {for (int i = 0; i < indentation; i++) {System.out.print(" ");}System.out.println(organization.getName());List<Organization> organizations = organization.getOrganizations();if (!organizations.isEmpty()) {organizations.forEach(sub -> {showOrganization(sub, indentation + 2);});}}
}