码迷,mamicode.com
首页 > 其他好文 > 详细

生成器模式

时间:2018-11-13 23:48:52      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:tst   ted   div   ringbuf   rac   char   city   技术分享   pen   

Intent

封装一个对象的构造过程,并允许按步骤构造。

Class Diagram

技术分享图片

 

Implementation

以下是一个简易的 StringBuilder 实现,参考了 JDK 1.8 源码。

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);
    }
}
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);
    }
}
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());
    }
}
abcdefghijklmnopqrstuvwxyz

JDK

  • java.lang.StringBuilder
  • java.nio.ByteBuffer
  • java.lang.StringBuffer
  • java.lang.Appendable
  • Apache Camel builders

生成器模式

标签:tst   ted   div   ringbuf   rac   char   city   技术分享   pen   

原文地址:https://www.cnblogs.com/AnXinliang/p/9955451.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!