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

Comments

  1. Builder is a nice pattern, good example.

    I'm not 100% sure about making it an "inner class", this is an interesting design question.

    I can see 'inner class' deals with protected field access and hides the 'builder' API away.

    Perhaps OTOH it could sometimes be a good idea to have the Builder API visible as a top-level class, since it is a crucial part of the lifecycle?

    Interesting snippet either way.

    LiterateJava.com

    ReplyDelete

Post a Comment

Popular posts from this blog

Apple's evaluating a new JVM

Tuning ext4 for performance with emphasis on SSD usage