考虑 Lecturer.java
中的以下代码。 Lecture.java 中的 setter 具有完全相同的形式。另请注意,感兴趣的属性是 private
。
public void setLecture(Lecture lecture) {
if (this.lecture == lecture) return;
if (this.lecture != null) {
this.lecture.setLecturer(null);
}
this.lecture = lecture;
if (this.lecture != null) {
this.lecture.setLecturer(this);
}
}
当尝试设置以前不是 null
的 null
值时,这会导致无限循环。
我不敢相信保持 1:1 关系的一致性如此困难 - 但我就是不知道如何做到这一点。如何解决这个问题?
最佳答案
最后,这是您的解决方案:
public class A {
private B b;
public void setB(B b) {
if(this.b != null) {
this.b.unsetA();
}
this.b = b;
if(b != null && b.getA() != this) {
this.b.setA(this);
}
}
public void unsetB() {
this.b = null;
}
public B getB() {
return b;
}
}
public class B {
private A a;
public void setA(A a) {
if(this.a != null) {
this.a.unsetB();
}
this.a = a;
if(a != null && a.getB() != this) {
this.a.setB(this);
}
}
public void unsetA() {
this.a = null;
}
public A getA() {
return a;
}
}
我的测试类:
public class Test {
public static void main(String ... args) {
A a1 = new A();
B b1 = new B();
A a2 = new A();
B b2 = new B();
checkForZeroOrTwoRelations(a1, a2, b1, b2);
a1.setB(b1);
checkForZeroOrTwoRelations(a1, a2, b1, b2);
b1.setA(a2);
checkForZeroOrTwoRelations(a1, a2, b1, b2);
b2.setA(a2);
checkForZeroOrTwoRelations(a1, a2, b1, b2);
b2.setA(null);
checkForZeroOrTwoRelations(a1, a2, b1, b2);
}
private static void checkForZeroOrTwoRelations(A a1, A a2, B b1, B b2) {
int i = 0;
if(a1.getB() != null) i++;
if(a2.getB() != null) i++;
if(b1.getA() != null) i++;
if(b2.getA() != null) i++;
if(i != 0 && i != 2) {
throw new IllegalStateException();
}
}
}
关于java - 如何保持一对一关系的一致性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27093660/