我正在使用构建器模式(如 Joshua Bloch's 中所解释的那样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}
.
有没有办法在不公开变量的情况下做到这一点?