Javaビルダーのデザインパターンの例

完全なJava builderパターン の例です。

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

上記のbuilderパターンを使用してStudentオブジェクトを作成する例

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"));
        ** /
    }

}

参考文献

Javaメソッドの多くのパラメータ、第3回:Builderパターン]

builder デザインパターン リンク://タグ/java/[java]