Java Builder(建造者)模式

2020-08-22  本文已影响0人  Solace_0e71

应用场景

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;
        }
    }
}

解析

上一篇下一篇

猜你喜欢

热点阅读