Java:组件如何知道其所有者

Java:组件如何知道其所有者,java,ownership,Java,Ownership,假设我有一个类a和一个类B public class A { private B b; public A() { this.b = new B(); } public B getB() { return this.b; } } public class B { public String getSome() { return "Get some!"; } } 我知道我可以通过A获得

假设我有一个类
a
和一个类
B

public class A {

    private B b;

    public A() {
        this.b = new B();
    }

    public B getB() {
        return this.b;
    }
}

public class B {

    public String getSome() {
        return "Get some!";
    }
}
我知道我可以通过A获得B,因为A拥有B:
newa().getB()


但是如果我有B,我能得到A吗?

当然,只需在类B中添加例程
getA()
,并将构造函数中的行更改为

public A() {
    this.b = new B(this);
}
当然,这假设您的类B有一个接受
a
的构造函数,例如

public B(A a) {
    this.a = a;
}

B
需要明确提及其所有者:

public class B {
  private final A owner;

  public B(A owner) {
    this.owner = owner;
  }

  public A getOwner() {
    return owner;
  }
}
A
中:

public A() {
  b = new B(this);
}

不,那是不可能的。您正在寻找反向引用,但如果需要,我们必须在代码中创建它们

如果希望收集B的所有引用,可以使用构造函数或创建B的工厂(模式)来完成。我将带工厂参观:

public class B {

   private static Set<? extends Object> referencers = new HashSet<? extends Object>();
   private B(){}  // no public constructor
   public static create(Object parent) {
     // cooperative approach, the caller should pass "this"
     referencers.add(parent);
   }
   public static remove(Object parent) {
     referencers.remove(parent);
   }
}
公共B类{

私有静态集否您不能。B没有对A的引用。


类a引用了类B,但类B没有引用类a。引用只是单向的。

如果需要B始终绑定到a的实例,请将B设为a的内部类:

class A {

    B b = new B();

    class B {
        String getSome() {
            // this will refer to the enclosing A
            return A.this.toString();
        }
    }
}

内部(非静态)类始终具有对封闭实例的隐式引用,没有它就无法存在。为了从外部实例化B,您需要一个讨厌的语法:
B=new a().new B();

您还可以使用内部类

包装试验

公共A类{

B b = null;

public B getB()
{
    return b;
}

public class B {

    public A getA()
    {
        return A.this;
    }
}

public static void main(String[] args) {
    B b = new A().new B();
}

}

没有。Java中没有“所有者”这类东西。任何对象都可以被任意数量的其他对象引用。

如果多个对象拥有(引用)一个
B
的实例会怎么样?每个
B
的实例都必须跟踪对它的所有引用。