Java builder design pattern example

A complete Java builder pattern example.

Student.java

package com.mkyong.model;

import java.util.List;

public class Student {

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

    public static class Builder {

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

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

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

Example to use above builder pattern to create a Student object.


package com.mkyong.model;

import java.util.Arrays;

public class TestStudent {

    public static void main(String[] args) {

        Student s = new Student.Builder()
			.name("mkyong")
			.age(18)
			.language(Arrays.asList("chinese","english"))
			.build();

		//Student{name='mkyong', age=18, language=[chinese, english]}
        System.out.println(s);

        // Classic way to create an object
		/*
		Student s = new Student();
        s.setName("mkyong");
        s.setAge(18);
        s.setLanguage(Arrays.asList("chinese","english"));
		*/

    }

}

References

  1. Wikipedia – Builder pattern
  2. Too Many Parameters in Java Methods, Part 3: Builder Pattern

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Tahir Hussain Mir Recent comment authors
newest oldest most voted
Tahir Hussain Mir
Guest
Tahir Hussain Mir

Student s = new Student.Builder()
.name(“mkyong”)
.age(18)
.language(Arrays.asList(“chinese”,”english”))
.build();
Are You 18 years old? :p ;)