对象参考案例研究

时间:2010-05-19 16:06:55

标签: java

当人1成为人3的伴侣的时候,人2不再有作为伴侣的人1,并且人4不再有作为伴侣的人3。我该怎么解决这个问题?

public class Person {

    private String name;
    private Person partner;

    public Person(String name){
        this.name = name;
    }

    public void setPartner(Person partner){
        this.partner = partner;
        partner.partner = this; 
    }

    public static void main(String[] args) {

        Person one = new Person("1");           
        Person two = new Person("2");
        Person three = new Person("3");
        Person four = new Person("4");

        one.setPartner(two);
        three.setPartner(four);

        one.setPartner(three);

        //Person two is still partner with person 1
        //and person four is still partner with person 3 
   }

7 个答案:

答案 0 :(得分:3)

public void setPartner(Partner b) {
  // Special case, otherwise we'll have troubles
  // when this.partner is already b.
  if (this.partner == b) return;

  if (this.partner != null) {
    this.partner.partner = null;
  }

  this.partner = b;

  // Make sure that the new partner has the right partner.
  // This will make sure the original b.partner has its
  // partner field nullified.
  // Note that if we don't have the special case above,
  // this will be an infinite recursion.
  b.setPartner(this);
}

答案 1 :(得分:2)

public void setPartner(Person partner){
    if (this.partner != null) {
        this.partner.partner = null; // Reset the partner of the old partner.
    }
    this.partner = partner;          // Assign new partner.
    this.partner.partner = this;     // Set the partner of the new partner.
}

答案 2 :(得分:1)

我认为将此作为setPartner中的第一行应该有效:this.partner.partner = null;

当然,您必须检查this.partner是否为null

答案 3 :(得分:1)

将setPartner更改为:

public void setPartner(Person partner){
    if(this.partner != null)
        this.partner.partner = null;
    this.partner = partner;
    partner.partner = this; 
}

答案 4 :(得分:1)

我建议您设置一个setRelationship方法,该方法会对当前setPartner采取Person行动,并对旧合作伙伴采取新的removePartner行动,如果不是空的。

新的setRelationship方法将会存在,以便不会混淆setPartner的作用 - 毫无疑问的程序员可能没有任何副作用。

答案 5 :(得分:0)

class Person {

  String name;
  Partnership partnership;
  void setPartnership(Partnership p) {
    partnership=p;
  }
}
class Partnership {
  Person partner1;
  Person partner2;
  public setPartners(Person p1,Person p2) {
    p1.setPartnership(this);
    p2.setPartnership(this);
}

理想情况下,您需要一种方法来阻止从伙伴关系以外的任何地方调用setPartnership。

答案 6 :(得分:-1)

这是我的代码:

public void setPartner(Person partner) {
    if (this.partner != null)
       this.partner.partner = null;
    this.partner = partner;
    if (partner.partner != null)
       partner.partner.partner = null;
    partner.partner = this;
}