Object reference case study
When person 1 become partner with person 3, person 2 should no longer 开发者_开发知识库have person 1 as partner and person 4 should no longer have person 3 as partner. How should I solve this?
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
}
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);
}
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.
}
change setPartner to:
public void setPartner(Person partner){
if(this.partner != null)
this.partner.partner = null;
this.partner = partner;
partner.partner = this;
}
I would suggest that you set up a setRelationship
method, which would action setPartner
on the current Person
, and action a new removePartner
on the old partner, if not null.
The new setRelationship
method would be in place so that there would be no confusion as to what setPartner
does - there would be no side-effects that might be missed by the unsuspecting programmer.
I think putting this as the first line in setPartner
should work: this.partner.partner = null;
Of course you must check if this.partner
is null
or not.
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);
}
Ideally you would want a way to prevent setPartnership being called from anywhere other than Partnership.
Here is my Code:
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;
}
精彩评论