Java Builder(建造者)模式

应用场景

1、对象的创建比较复杂,有顺序限制或者组合依赖
2、构建对象的参数比较多,并且包含较多可选参数

构建实例

public class BillingtestClient {
    private BillingtestClient() {
    }

    public static Builder builder() {
        return new DefaultBuilder();
    }  

    public interface Builder {
        public Builder httpRequestConfig(HttpRequestConfig httpRequestConfig);
        public BillingtestClient build() throws Exception;
    }
    private static class DefaultBuilder implements Builder {

        private  BillingtestClient billingtestClient;

        public DefaultBuilder() {
            billingtestClient = new BillingtestClient();
        }

        @Override
        public Builder httpRequestConfig(HttpRequestConfig httpRequestConfig) {
            billingtestClient.httpRequestConfig = httpRequestConfig;
            return this;
        }

        @Override
        public BillingtestClient build() throws Exception {
              return billingtestClient;
        }
    }
}

解析

  • 类构造器设置为私有
  • 创建类实例设置为public builder创建DefaultBuilder,DefaultBuilder实现了Builder接口,接口中定义需要设置的属性值,以及最后的build返回设置完的类实例

你可能感兴趣的:(Java Builder(建造者)模式)