Builder Pattern in Effective Java Builder Pattern in Effective Java java java

Builder Pattern in Effective Java


Make the builder a static class. Then it will work. If it is non-static, it would require an instance of its owning class - and the point is not to have an instance of it, and even to forbid making instances without the builder.

public class NutritionFacts {    public static class Builder {    }}

Reference: Nested classes


You should make the Builder class as static and also you should make the fields final and have getters to get those values. Don't provide setters to those values. In this way your class will be perfectly immutable.

public class NutritionalFacts {    private final int sodium;    private final int fat;    private final int carbo;    public int getSodium(){        return sodium;    }    public int getFat(){        return fat;    }    public int getCarbo(){        return carbo;    }    public static class Builder {        private int sodium;        private int fat;        private int carbo;        public Builder sodium(int s) {            this.sodium = s;            return this;        }        public Builder fat(int f) {            this.fat = f;            return this;        }        public Builder carbo(int c) {            this.carbo = c;            return this;        }        public NutritionalFacts build() {            return new NutritionalFacts(this);        }    }    private NutritionalFacts(Builder b) {        this.sodium = b.sodium;        this.fat = b.fat;        this.carbo = b.carbo;    }}

And now you can set the properties as follows:

NutritionalFacts n = new NutritionalFacts.Builder().sodium(10).carbo(15).fat(5).build();


To generate an inner builder in Intellij IDEA, check out this plugin: https://github.com/analytically/innerbuilder