2014-05-17

Builder Pattern in Java

The builder pattern can be used to provide a kind of virtual dynamically extendable constructor to build e.g. a model class for RESTful requests where not all fields are required but many fields are optional.
public class ClientRequestModel {
    private String url;
    private String headers;
    private String parameters;
    private String body;

    public ClientRequestModel(Builder builder) {
        url = builder.url;
    }

    public String getUrl() {
        return url;
    }

    public String getHeaders() {
        return headers;
    }

    public String getParameters() {
        return parameters;
    }

    public String getBody() {
        return body;
    }

    @Override
    public String toString() {
        return url;
    }

    public static class Builder {
        private String url;
        private String headers;
        private String parameters;
        private String body;

        public Builder url(String url) {
            this.url = url;
            return this;
        }

        public Builder headers(String headers) {
            this.headers = headers;
            return this;
        }

        public Builder parameters(String parameters) {
            this.parameters = parameters;
            return this;
        }

        public Builder body(String body) {
            this.body = body;
            return this;
        }

        public ClientRequestModel build() {
            return new ClientRequestModel(this);
        }
    }

And to construct / build an instance of the ClientRequestModel you just need to call something like:

        ClientRequestModel clientRequestModel =
                new ClientRequestModel.Builder()
                        .url("http://www.example.com") // url, is an optional field
                                // many other optional fields to add
                        .build();