建造者模式(Builder Pattern)属于创建型模式,它提供了一种创建对象的最佳方式。
它将一个复杂的对象的构建分成多个简单的步骤。
当一个类的构造函数参数个数超过4个,而且这些参数有些是可选的参数,考虑使用建造者模式
建造者实现步骤:
1、在Setting 中创建一个静态内部类 Builder(私有化构造),然后将 Setting中的属性都复制到Builder类中
2、在Setting 中创建一个 builder()方法,用于实例化Builder
3、在Setting 中创建一个private的构造函数,参数为Builder类型,将Builder内的属性赋值给Setting内的属性
4、Builder中创建设置函数,对Setting中那些可选参数进行赋值,返回值为Builder类型的实例
5、在Builder中创建一个builder()方法,在其中构建Setting的实例并返回
代码:
public class Settings { private final int maxSize; private final int minSize; private final int maxWaitQueueSize; private final long maxWaitTimeMS; /** * 返回建造器的实例 */ public static Builder builder() { return new Builder(); } /** * 私有化构造,参数为Builder,用于创建Setting实例并初始化属性 */ private Settings(final Builder builder) { maxSize = builder.maxSize; minSize = builder.minSize; maxWaitQueueSize = builder.maxWaitQueueSize; maxWaitTimeMS = builder.maxWaitTimeMS; } /** * 建造器 */ public static final class Builder { private int maxSize; private int minSize; private int maxWaitQueueSize; private long maxWaitTimeMS; private Builder() { } public Builder maxSize(final int maxSize) { this.maxSize = maxSize; return this; } public Builder minSize(final int minSize) { this.minSize = minSize; return this; } public Builder maxWaitQueueSize(final int maxWaitQueueSize) { this.maxWaitQueueSize = maxWaitQueueSize; return this; } public Builder maxWaitTimeMS(final long maxWaitTimeMS) { this.maxWaitTimeMS = maxWaitTimeMS; return this; } public Settings build() { return new Settings(this); } } /** * Setting 的getter方法 */ public int getMaxSize() { return maxSize; } public int getMinSize() { return minSize; } public int getMaxWaitQueueSize() { return maxWaitQueueSize; } public long getMaxWaitTimeMS() { return maxWaitTimeMS; } }
使用建造器创建Setting实例:
Settings settings = Settings.builder() .minSize(1) .maxSize(2) .maxWaitQueueSize(5) .maxWaitTimeMS(1000L) .build();
END.