Java builder design pattern example
By:Roy.LiuLast updated:2019-08-17
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
From:一号门
Previous:Java 8 Convert List to Map
COMMENTS