需要在一个页面中,展示出学校的院系组成,一个学校有多个学院,一个学院有多个系
当需要处理的对象能够生成树形结构,而需要对树的结点和叶子进行操作时,它能够提供一直的方式,不论是结点还是叶子
/***
* @author shaofan
* @Description 组合模式解决院系展示问题
*/
public class Composite {
public static void main(String[] args) {
Department department = new Department("软件工程","软件");
Department department2 = new Department("计算机科学与技术","计算");
College college1 = new College("计算机学院","计算机学院");
College college2 = new College("艺术学院","艺术学院");
University university = new University("xx大学","大学");
college1.add(department);
college1.add(department2);
university.add(college1);
university.add(college2);
university.print();
}
}
abstract class OrganizationComponent{
private String name;
private String desc;
public OrganizationComponent(String name,String desc){
this.name = name;
this.desc = desc;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
// 增加方法和修改方法默认实现,抛出不支持操作的异常
protected void add(OrganizationComponent organizationComponent){
throw new UnsupportedOperationException();
}
protected void remove(OrganizationComponent organizationComponent){
throw new UnsupportedOperationException();
}
/**
* 抽象的打印方法,具体有子类实现
*/
protected abstract void print();
}
class University extends OrganizationComponent{
List<OrganizationComponent> colleges = new ArrayList<>();
public University(String name, String desc) {
super(name, desc);
}
@Override
protected void add(OrganizationComponent organizationComponent) {
colleges.add(organizationComponent);
}
@Override
protected void remove(OrganizationComponent organizationComponent) {
colleges.remove(organizationComponent);
}
@Override
protected void print() {
System.out.println("----------"+getName()+"------------"+getDesc()+"---------------");
for (OrganizationComponent college : colleges) {
college.print();
}
}
}
class College extends OrganizationComponent{
List<OrganizationComponent> departments = new ArrayList<>();
public College(String name, String desc) {
super(name, desc);
}
@Override
protected void add(OrganizationComponent organizationComponent) {
departments.add(organizationComponent);
}
@Override
protected void remove(OrganizationComponent organizationComponent) {
departments.remove(organizationComponent);
}
@Override
protected void print() {
System.out.println("------"+getName()+"------"+getDesc()+"-------");
for (OrganizationComponent department : departments) {
department.print();
}
}
}
class Department extends OrganizationComponent{
public Department(String name, String desc) {
super(name, desc);
}
// 叶子结点不实现管理方法
@Override
protected void print() {
System.out.println(getName()+"--"+getDesc());
}
}
在Java中的HashMap使用了组合模式