建造者模式(Builder Pattern)

2024/3/27 Java进阶

  • 一个通用容器(对象、集合),按构建者的意愿自定义顺序放入内容,从而建造出不同对象成品。
  • 最佳实例:StringBuilder。

# 1、StringBuilder实例

public class AbstractStringBuilder {
    protected char[] value;

    protected int count;

    public AbstractStringBuilder(int capacity) {
        count = 0;
        value = new char[capacity];
    }

    public AbstractStringBuilder append(char c) {
        ensureCapacityInternal(count + 1);
        value[count++] = c;
        return this;
    }

    private void ensureCapacityInternal(int minimumCapacity) {
        // overflow-conscious code
        if (minimumCapacity - value.length > 0)
            expandCapacity(minimumCapacity);
    }

    void expandCapacity(int minimumCapacity) {
        int newCapacity = value.length * 2 + 2;
        if (newCapacity - minimumCapacity < 0)
            newCapacity = minimumCapacity;
        if (newCapacity < 0) {
            if (minimumCapacity < 0) // overflow
                throw new OutOfMemoryError();
            newCapacity = Integer.MAX_VALUE;
        }
        value = Arrays.copyOf(value, newCapacity);
    }
}
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
31
32
33
34
public class StringBuilder extends AbstractStringBuilder {
    public StringBuilder() {
        super(16);
    }

    @Override
    public String toString() {
        // Create a copy, don't share the array
        return new String(value, 0, count);
    }
}
1
2
3
4
5
6
7
8
9
10
11
public class ClientTest {

    public static void main(String[] args) {
        StringBuilder builder = new StringBuilder();
        builder.append("步骤1");
        builder.append("步骤2");
        builder.append("步骤3");
        builder.append("步骤4");
        builder.append("步骤5");
        System.out.println(builder);
    }
}
// 输出结果:步骤1步骤2步骤3步骤4步骤5
1
2
3
4
5
6
7
8
9
10
11
12
13