Полный шаблон Java builder пример.
package com.mkyong.model; import java.util.List; public class Student { private String name; private int age; private Listlanguage; public static class Builder { private String name; private int age; private List 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 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 + '}'; } }
Пример использования приведенного выше шаблона конструктора для создания объекта учащегося.
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")); */ } }
Рекомендации
Оригинал: “https://mkyong.com/design-pattern/java-builder-design-pattern-example/”