ビルダーパターン

effectiveJava 2nd Editionより、
『数多くのコンストラクタパラメータに直面した時にはビルダーを検討する』

/**
 * No2.builder pattern
 * @author User
 *
 */

public class Person {
    private final int age;
    private final String name;
    private String city;
    private String job;
    private String address;
    private String phoneNumber;

    //ビルダーを引数に持つコンストラクタ.privateにすることでビルダーでのインスタンス生成を強制する
    private Person(PersonBuilder personBuilder) {
        this.age = personBuilder.age;
        this.name = personBuilder.name;
        this.city = personBuilder.city;
        this.job = personBuilder.job;
        this.address = personBuilder.address;
        this.phoneNumber = personBuilder.phoneNumber;
    }

    /**
    * Personを生成するビルダー.
    * @author User
    *
    */
    public static class PersonBuilder {
        
        private final int age;
        private final String name;
        
        private String city;
        private String job;
        private String address;
        private String phoneNumber;
        
        public PersonBuilder(int age, String name) {
            this.age = age;
            this.name = name;
        }
        public PersonBuilder city(String city) {
            this.city = city;
            return this;
        }
        public PersonBuilder job(String job) {
            this.job = job;
            return this;
        }
        public PersonBuilder address(String address) {
            this.address = address;
            return this;
        }
        public PersonBuilder phoneNumber(String phoneNumber) {
            this.phoneNumber = phoneNumber;
            return this;
        }
        //最終的にこの#build()を呼び出すことでPersonオブジェクトが生成される
        public Person build() {
            return new Person(this);
        }
    }
}

呼び出し側

public class Main {
    
    public static void main(String[] args) {
        //生成するときはビルダーのインスタンスメソッドをメソッドチェーンにて呼び出す
        Person person = new Person.PersonBuilder(20, "tokyo").city("tokyo").job("teacher").address("shinagawa").build();
    }
}

EFFECTIVE JAVA 第2版 (The Java Series)

EFFECTIVE JAVA 第2版 (The Java Series)