最後,這裏是你的解決方案:
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();
}
}
}
@Ogen該屬性應該是私人的。 – 2014-11-23 20:11:08
既然有一個二傳手我想也有一個吸氣,對吧? – 2014-11-23 20:45:21
@giannischristofakis Yessir。 – 2014-11-23 20:45:53