在Java FX应用程序中使用属性,我遇到了关于理解属性用法的问题:使用类实例成员的实际区别是什么......财产反对简单...财产?
public class Foo {
private IntegerProperty id;
public Foo(int id) {
this.id = new SimpleIntegerProperty(id);
}
public IntegerProperty idProperty() {
return this.id;
}
public int getId() {
return id.get();
}
public void setId(int id) {
this.id.set(id);
}
}
对
public class Foo {
private SimpleIntegerProperty id;
public Foo(int id) {
this.id = new SimpleIntegerProperty(id);
}
public SimpleIntegerProperty idProperty() {
return this.id;
}
public int getId() {
return id.get();
}
public void setId(int id) {
this.id.set(id);
}
}
你的第一个实现确实很好。
您绝对应该尽可能使用最抽象的类型(在您的例子中为 IntegerProperty)。
主要原因是它允许您更改实现而无需更改方法的原型/定义,因此无需更改任何调用者。
考虑 Set 的相同情况,并从 HashSet 具体类型迁移到 LinkedHashSet。