我正在练习Java并遇到问题。我想使setPartner方法动态化,在p1和p2作为伙伴连接的情况下,如果我决定在p1和p3上调用setPartner(),则p2会断开连接。我该如何实现?

public class Partner {

    private final String name;
    private Partner partner;
    private Partner unlinked;

    public Partner(String name) {
        this.name = name;
        partner = null;
    }

    public String getName() {
        return name;
    }

    public Partner getPartner(){
        if (partner != null){
            return partner;
        }
        else {
            return null;
        }
    }

    public void setPartner(Partner p1, Partner p2){
        if(p1 == null || p2 == null){
            p1.partner = null;
            p2.partner = null;
        }
        else{
            p1.partner = p2;
            p2.partner = p1;
            System.out.println(unlinked);
        }

    }


    public static void main(String[] args) {
        Partner p1 = new Partner("JohnP1");     // Create Partner Objects
        Partner p2 = new Partner("JaneP2");
        Partner p3 = new Partner("JacksonP3");

     //   System.out.println(p1.getName());           // Test names
     //   System.out.println(p2.getName());

        p1.setPartner(p1,p2);                       // set partners and test if relation works
        p1.setPartner(p1,p3);

        System.out.println(p2.getPartner().getName());

        //p1.setPartner(p1, null);                    // test for null
        //System.out.println(p2.getPartner().getName());



    }
}

最佳答案

您可以执行以下操作:

public class Partner {
    private final String name;
    private Partner partner;

    public Partner(String name) {
        if (name == null) throw new NullPointerException();
        this.name = name;
    }

    public Partner getPartner() {
        return partner;
    }

    public void setPartner(Partner p) {
        // this is critical, or else we'll call each other forever in a loop
        if (partner == p) {
            // we're already partners with p; nothing to do
            return;
        }

        if (partner != null) {
            // already have a partner; tell them we're leaving, directly
            partner.partner = null;  // (we don't want them to call us back)
        }
        partner = p;
        if (p != null) {
            // new partner; let them know about us
            p.setPartner(this);
        }
    }
}


最初,它是在没有伙伴的情况下创建的。我看不到unlinked字段或getPartner中的测试,这毫无意义。所有工作都在setPartner中完成;有关详细信息,请参见此处的评论。

更新:

当我们将伙伴的伙伴设置为null告诉他们我们要离开时,我们必须直接执行此操作,而不是通过调用他们的set方法来进行,否则他们会立即回电话告诉他们他们要离开我们。我敢肯定,与人际关系的任何关系纯属巧合。该答案的早期版本存在严重的错误。

08-04 07:51