diff --git a/notes/设计模式.md b/notes/设计模式.md index 9742e1b9..3e159d50 100644 --- a/notes/设计模式.md +++ b/notes/设计模式.md @@ -339,7 +339,7 @@ public class ConcreteFactory2 extends Factory { ### 类图 -

+

抽象工厂模式创建的是对象家族,也就是很多对象而不是一个对象,并且这些对象是相关的,也就是说必须一起创建出来。而工厂模式只是用于创建一个对象,这和抽象工厂模式有很大不同。 @@ -433,9 +433,83 @@ public class Client { ### 意图 -定义一个新的类来构造另一个类的实例,以创建一个复杂的对象。 +封装一个对象的构造过程,并允许按步骤构造。 -它可以封装一个对象的构造过程,并允许按步骤构造。 +### 类图 + +

+ +### 实现 + +以下是一个简易的 StringBuilder 实现,参考了 JDK 1.8 源码。 + +```java +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); + } +} +``` + +```java +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); + } +} +``` + +```java +public class Client { + public static void main(String[] args) { + StringBuilder sb = new StringBuilder(); + final int count = 26; + for (int i = 0; i < count; i++) { + sb.append((char) ('a' + i)); + } + System.out.println(sb.toString()); + } +} +``` + +```html +abcdefghijklmnopqrstuvwxyz +``` ### JDK diff --git a/pics/13b0940e-d1d7-4b17-af4f-b70cb0a75e08.png b/pics/13b0940e-d1d7-4b17-af4f-b70cb0a75e08.png new file mode 100644 index 00000000..27f1c9f1 Binary files /dev/null and b/pics/13b0940e-d1d7-4b17-af4f-b70cb0a75e08.png differ diff --git a/pics/8668a3e1-c9c7-4fcb-98b2-a96a5d841579.png b/pics/8668a3e1-c9c7-4fcb-98b2-a96a5d841579.png new file mode 100644 index 00000000..9eda1deb Binary files /dev/null and b/pics/8668a3e1-c9c7-4fcb-98b2-a96a5d841579.png differ