模式介绍
组合模式(Composite Pattern),又叫部分整体模式,是用于把一组相似的对象当作一个单一的对象。组合模式依据树形结构来组合对象,用来表示部分以及整体层次。这种类型的设计模式属于结构型模式,它创建了对象组的树形结构。
模式优点
1、高层模块调用简单。
2、节点自由增加。
模式缺点
1、在使用组合模式时,其叶子和树枝的声明都是实现类,而不是接口,违反了依赖倒置原则。
使用场景
1、您想表示对象的部分-整体层次结构(树形结构)。
2、您希望用户忽略组合对象与单个对象的不同,用户将统一地使用组合结构中的所有对象。
3、部分、整体场景,如树形菜单,文件、文件夹的管理。
系统建模
1、把学校、院、系都看作组织机构,他们之间没有继承关系,而是树形结构,可以更好的实现管理操作。
系统实现
/**
* 组织抽象类
*/
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个系!
我是系!