Friday

Java builder design pattern example

import java.util.List;

public class Student {

    private String name;
    private int age;               //optional
    private List<String> language; //optinal

    public static class Builder {

        private String name;
        private int age;
        private List<String> language;

        public Builder (String name) {
            this.name = name;
        }

        public Builder age(int age) {
            this.age = age;
            return this;
        }

        public Builder language(List<String> language) {
            this.language = language;
            return this;
        }

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

    }

    private Student(Builder builder) {
        name = builder.name;
        age = builder.age;
        language = builder.language;
    }

    @Override
    public String toString() {
        return "Student{" + "name='" + name + '\'' + ", age=" + age + ", language=" + language +'}';
    }
}

import java.util.Arrays;

public class TestStudent {

    public static void main(String[] args) {

       Student s1 = new Student.Builder("eda").build();
      
        Student s2 = new Student.Builder("eda").age(28).language(Arrays.asList("japanese","english")).build();

        System.out.println("s1--> " + s1);
        System.out.println("s2--> " + s2);
    }

}
Output:
s1--> Student{name='eda', age=0, language=null}
s2--> Student{name='eda', age=28, language=[japanese, english]}


Quoting from Joshua Bloch's Second Edition of Effective Java:
"In summary, the Builder pattern is a good choice when designing classes
whose constructors or static factories would have more than a handful of
parameters, especially if most of those parameters are optional."

No comments:

Post a Comment