组合模式
业务需求
- 学校展示院系结构,一个学校有多个学院,一个学院有多个系;
- 传统思路,系继承学院,学院继承学校;
问题分析
- 将学院看做是学校的子类,系是学院的子类,这样实际上是站在组织大小来进行分层次的
- 实际我们要求是,一个学校有多个学院,一个学院有多个系;传统的方案不能很好实现管理操作,比如对学院、系的添加、删除、遍历等
- 解决方案:把学校、院、系看做组织结构,他们之间没有继承关系,而是一个树形结构,可以更好实现管理操作
基本介绍
- 组合模式,又叫部分整体模式,它创建了对象组的树形结构,将对象组合成树状结构,表示整体-部分的层次关系
- 组合模式一句树形结构来组合对象,用来表示部分以及整体层次
- 这种类型的设计模式属于结构型模式
- 组合模式是用户对单个对象和组合对象的访问具有一致性,即组合能让客户以一致的方式处理个别对象以及组合对象
原理图说明
- Component:这是组合中对象声明接口,在适当情况下,实现所有类共有的接口默认行为,用于访问和管理Component子部件,可以使抽象类或接口
- Leaf:在组合中表示叶子节点,叶子节点没有子节点,充当被管理者
- Composite:非叶子节点,用于存储子部件,在Component接口中实现子部件的相关操作,比如增加、删除;充当管理者
解决的问题 - 组合模式解决这样的问题,当我们要处理的对象可以生成一棵树形结构,而我们要对树上的节点和叶子进行操作时,它能提供一致的方式,而不用考虑他是节点还是叶子
代码实现
组织机构父类,可以是普通类、抽象类、接口
默认实现的方法作用在于,根据下边的节点是否为叶子节点,决定是否可以使用父类方法
@Data
public abstract class OrganizationComponent {
private String name;
private String des;
public OrganizationComponent(String name, String des) {
super();
this.name = name;
this.des = des;
}
protected void add(OrganizationComponent organizationComponent) {
// 默认实现
throw new UnsupportedOperationException();
}
protected void remove(OrganizationComponent organizationComponent) {
// 默认实现
throw new UnsupportedOperationException();
}
// 子类都需要实现
protected abstract void print();
}
定义大学类
public class University extends OrganizationComponent{
List<OrganizationComponent> list = new ArrayList<>();
public University(String name, String des) {
super(name, des);
}
@Override
protected void add(OrganizationComponent organizationComponent) {
list.add(organizationComponent);
}
@Override
protected void remove(OrganizationComponent organizationComponent) {
list.remove(organizationComponent);
}
// 输出当前University所包含的学院
@Override
protected void print() {
System.out.println("============="+getName()+"===============");
for (OrganizationComponent o : list) {
o.print();
}
}
}
定义学院类
public class College extends OrganizationComponent{
List<OrganizationComponent> list = new ArrayList<>();
public College(String name, String des) {
super(name, des);
}
@Override
protected void add(OrganizationComponent organizationComponent) {
list.add(organizationComponent);
}
@Override
protected void remove(OrganizationComponent organizationComponent) {
list.remove(organizationComponent);
}
// 输出当前College所包含的学院
@Override
protected void print() {
System.out.println("============="+getName()+"===============");
for (OrganizationComponent o : list) {
o.print();
}
}
}
定义具体系
public class Department extends OrganizationComponent{
public Department(String name, String des) {
super(name, des);
}
// 叶子节点不具备增删,add和remove不再重写
@Override
protected void print() {
System.out.println(getName());
}
}
客户端
public class Client {
public static void main(String[] args) {
// 创建学校
OrganizationComponent university = new University("清华大学", "中国名校");
// 创建学院
OrganizationComponent computerCollege = new College("计算机学院", "计算机学院");
OrganizationComponent infoEngineerCollege = new College("信息工程学院", "信息工程学院");
// 创建系
computerCollege.add(new Department("软件工程", "软件工程真不错"));
computerCollege.add(new Department("网络工程", "网络工程也不错"));
computerCollege.add(new Department("计算机科学与技术", "计算机科学与技术还可以"));
infoEngineerCollege.add(new Department("通信工程", "通信工程不好学"));
infoEngineerCollege.add(new Department("信息工程", "信息工程太难了"));
// 学院添加到学校中
university.add(computerCollege);
university.add(infoEngineerCollege);
// 需要查看哪个级别,直接输出即可
university.print();
System.out.println("##################分割线####################");
computerCollege.print();
}
}
JDK源码分析—HashMap
Demo
public class Composite {
public static void main(String[] args) {
Map<Integer, String> hashMap = new HashMap<>();
// 存入叶子节点
hashMap.put(0, "水浒传");
Map<Integer, String> map = new HashMap<>();
map.put(1, "西游记");
map.put(2, "红楼梦");
// 存入节点
hashMap.putAll(map);
System.out.println(hashMap);
}
}
源码片段
public interface Map<K, V> {
...
V put(K var1, V var2);
...
void putAll(Map<? extends K, ? extends V> var1);
public abstract class AbstractMap<K,V> implements Map<K,V> {
...
public V put(K key, V value) {
throw new UnsupportedOperationException();
}
...
public void putAll(Map<? extends K, ? extends V> m) {
for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
put(e.getKey(), e.getValue());
}
}
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {
...
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
...
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
...
return null;
}
...
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
}
说明
- Map就是一个抽象的构建(类似于前面的Component)
- HashMap是一个中间构建(Composite),实现/继承了相关方法put/putAll
- Node是HashMap的静态内部类,类似于Leaf叶子节点,没有put/putAll
注意实现和细节
- 简化客户端操作,客户端只需要面对一致的对象而不用考虑整体部分或者叶子节点的问题
- 具有较强强的扩展性,当我们要更改组合对象时,我们只需要调整内部的层次关系,客户端就不用做出任何改动
- 方便创建出复杂的层次结构,客户端不用理会组合里面的组成细节,容易添加节点或者叶子从而创建出复杂的树形结构
- 需要遍历组织机构,或者处理的对象具有属性结构时,非常适合使用组合模式
- 要求较高的抽象性,如果节点和叶子有很多差异性,比如很多方法和属性不一样,则不适合使用组合模式