模式介绍
组合模式,又叫部分整体模式,用于把一组相似的对象当作一个单一的对象。组合模式依据树形结构来组合对象,用来表示部分以及整体层次。组合模式使得用户对单个对象和组合对象的使用具有一致性。它在我们树型结构的问题中,模糊了简单元素和复杂元素的概念,客户程序可以像处理简单元素一样来处理复杂元素,从而使得客户程序与复杂元素的内部结构解耦。
使用场景
1、您想表示对象的部分-整体层次结构(树形结构)。
2、您希望用户忽略组合对象与单个对象的不同,用户将统一地使用组合结构中的所有对象。
3、部分、整体场景,如树形菜单,文件、文件夹的管理。
系统实现
/**
* 组织抽象类
*/
public abstract class OrganizationComponent {
private String name;
public OrganizationComponent(String name){
this.name = name;
}
public void add(OrganizationComponent organizationComponent){
throw new UnsupportedOperationException();
}
public void remove(OrganizationComponent organizationComponent){
throw new UnsupportedOperationException();
}
public abstract void print();
}
import java.util.ArrayList;
import java.util.List;
/**
* 大学类
*/
public class University extends OrganizationComponent{
List<OrganizationComponent> college = new ArrayList<>();
public University(String name){
super(name);
}
@Override
public void print(){
System.out.println("我是大学,有"+college.size()+"个学院!");
}
@Override
public void add(OrganizationComponent organizationComponent){
college.add(organizationComponent);
}
@Override
public void remove(OrganizationComponent organizationComponent){
college.remove(organizationComponent);
}
}
import java.util.ArrayList;
import java.util.List;
/**
* 学院类
*/
public class College extends OrganizationComponent{
List<OrganizationComponent> department = new ArrayList<>();
public College(String name){
super(name);
}
@Override
public void print(){
System.out.println("我是学院,有"+department.size()+"个系!");
}
@Override
public void add(OrganizationComponent organizationComponent){
department.add(organizationComponent);
}
@Override
public void remove(OrganizationComponent organizationComponent){
department.remove(organizationComponent);
}
}
**
* 系类
*/
public class Department extends OrganizationComponent{
public Department(String name){
super(name);
}
@Override
public void print(){
System.out.println("我是系!");
}
}
/**
* 客户端
*/
public class Client {
public static void main(String args[]){
University university = new University("大学");
College college = new College("学院");
Department department = new Department("系");
university.add(college);
college.add(department);
university.print();
college.print();
department.print();
}
}
结果:
我是大学,有1个学院!
我是学院,有1个系!
我是系!