私はいくつかのことにビルダーパターン(Joshua Blochで説明されているようにEffective Java
)を使用していますが、特に厄介な繰り返しが含まれています:
public class Foo {
private String name;
private int age;
public static class Builder implements IBuilder {
private String name;
private int age;
Builder name(String value) {
name = value;
return this;
}
Builder age(int value) {
age = value;
return this;
}
Foo build() {
return new Foo(this);
}
}
private Foo(Builder builder) {
name = builder.name;
age = builder.age;
}
}
小さいですが、面倒です。各クラスで変数を宣言する必要があります。フィールドを使用してクラスを作成し、そのクラスを拡張しようとしましたが、エラーが発生しました:{variable_name} has private access in {class_name}
。
変数を公開せずにこれを行う方法はありますか?