在 Java FX 应用程序中使用属性 我开始质疑对属性用法的理解:使用类实例成员 ...Property 与 Simple...Property 的实际区别是什么?
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)。
主要原因是它允许您更改实现而无需更改方法的原型(prototype)/定义,因此无需更改任何调用方。
考虑与 Set 相同的情况,并从 HashSet 具体类型迁移到 LinkedHashSet。
关于java - SimpleProperties 用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53890520/