# 集合框架中的设计模式

作者:Ethan.Yang
博客:https://blog.ethanyang.cn (opens new window)


基于JDK11进行分析, 大部分公司已经开始使用JDK11

# 一、迭代器模式(Iterator Pattern)

作用:统一遍历集合元素,屏蔽内部实现细节。

源码示例

ArrayList 为例:

public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
    // 内部数组存储元素
    transient Object[] elementData;

    // 返回迭代器对象
    public Iterator<E> iterator() {
        return new Itr();
    }

    private class Itr implements Iterator<E> {
        int cursor;       // 下一个要返回元素的索引
        int lastRet = -1; // 上一次返回元素的索引

        public boolean hasNext() {
            return cursor != size;
        }

        @SuppressWarnings("unchecked")
        public E next() {
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

说明

  • iterator() 返回内部迭代器对象,用户通过该迭代器遍历集合。
  • 隐藏了底层数组结构,实现统一访问接口。

# 二、工厂模式(Factory Pattern)

作用:通过静态方法隐藏实例创建细节,便于控制和扩展。

源码示例

Collections 工具类中的不可修改集合:

public static <T> List<T> unmodifiableList(List<? extends T> list) {
    return new UnmodifiableList<>(list);
}

static class UnmodifiableList<E> extends Collections.UnmodifiableCollection<E> implements List<E> {
    final List<? extends E> list;

    UnmodifiableList(List<? extends E> list) {
        super(list);
        this.list = list;
    }

    public E get(int index) {
        return list.get(index);
    }
    
    // 其他方法委托给内部list实现,只是不允许修改操作
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

说明

  • 通过工厂方法返回包装后的不可修改列表实例。
  • 用户无需关心具体实现细节,调用统一接口。

# 三、装饰者模式(Decorator Pattern)

作用:动态给对象增加额外功能。

源码示例

Collections.checkedCollection 为例,运行时类型检查:

public static <E> Collection<E> checkedCollection(Collection<E> c, Class<E> type) {
    return new CheckedCollection<>(c, type);
}

static class CheckedCollection<E> implements Collection<E>, Serializable {
    final Collection<E> c;
    final Class<E> type;

    CheckedCollection(Collection<E> c, Class<E> type) {
        this.c = Objects.requireNonNull(c);
        this.type = Objects.requireNonNull(type);
    }

    public boolean add(E e) {
        typeCheck(e);
        return c.add(e);
    }

    void typeCheck(Object o) {
        if (!type.isInstance(o))
            throw new ClassCastException("Attempt to insert " +
                o.getClass() + " element into collection with element type " +
                type);
    }

    // 其他方法委托给 c
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

说明

  • 通过装饰原集合,在添加元素时增加类型检查逻辑。
  • 不改变原集合代码,灵活增强功能。

# 四、单例模式(Singleton Pattern)

作用:全局唯一实例。

源码示例

Collections.emptyList()

private static final List EMPTY_LIST = new EmptyList<>();

@SuppressWarnings("unchecked")
public static final <T> List<T> emptyList() {
    return (List<T>) EMPTY_LIST;
}

static class EmptyList<E> extends AbstractList<E> implements RandomAccess, Serializable {
    public E get(int index) {
        throw new IndexOutOfBoundsException("Index: "+index);
    }
    public int size() {
        return 0;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

说明

  • 共享空集合单例,避免重复创建空对象。
  • 节约内存,提升性能。