1

Assume I have a Warehouse class. That Warehouse has a TradeDesk. That TradeDesk computes available items to sell based on an instance variable set in Warehouse. A Warehouse's constructor instantiates a TradeDesk, but because TradeDesk needs an instance variable from the incompletely initialized Warehouse, we have a problem. Short of passing the instance value through multiple constructors (which I'd rather avoid; note that the below example is significantly simplified), how do I solve this? Thanks!

public class Warehouse {
    TradingDesk td;
    public int val;

    public Warehouse() {
        val = 3;
        td = new TradingDesk(this);
    }
// New class
public class TradingDesk {
    Warehouse associatedWh;
    int val;
    public TradingDesk(Warehouse wh) {
        associatedWh = wh;
        val = associatedWh.val;
    }
}

}

4

3 回答 3

1

关于您的内部类代码,您尝试Warehouse使用外部类的实例初始化该字段。所以代码变成:

public class Warehouse {
    private TradingDesk td = new TradingDesk();
    private int val = 3;

    class TradingDesk {
         // you have already access to the outer Warehouse class including its fields
    }
}

实际上,内部类可以访问外部类的所有属性。所以你的问题就消失了。

编辑 - - - - - - - - -

这是我处理循环依赖的解决方案:

public class Warehouse {
    private TradingDesk td = new TradingDesk();
    private int val = 3;

    public int getVal(){ //so accessible through TradingDesk object
        return val;
    }

    public void associateWhToTd(){
        td.setAssociatedWh(this); // no issue here since "this" is fully already created
    }

    public static void main(String[]args){ // example of usage
        Warehouse wh = new Warehouse();
        wh.associateWhToTd();
    }
}

public class TradingDesk {
    Warehouse associatedWh;

    public void setAssociatedWh(Warehouse wh){
       this.associatedWh = wh;
    }
}
于 2012-10-31T01:36:06.057 回答
1

好吧,您可以创建TradingDesk一个内部类WareHouse. 这样,它可以直接访问其封闭WareHouse的实例变量,而无需传递任何参数,并且可以仅在实例的上下文中创建它的WareHouse实例。

public class Warehouse {

    private int val;
    private TradingDesk td;

    public Warehouse() {
        this.val = 3;
        this.td = new TradingDesk();
    }

    public class TradingDesk {

        public TradingDesk() {
            //this is the right way to access the enclosing instance
           if(WareHouse.this.val==3){
               //do something
           }
        }

        public WareHouse getAssociatedWareHouse(){
           return WareHouse.this;
        }
    }
}
于 2012-10-31T01:37:35.817 回答
0

您可以使用延迟实例化的子对象:

class Warehouse {
  private TradingDesk td;
  ...

  public Warehouse() {
    ...
  }

  public TradingDesk getTradingDesk() {
    if (td == null) td = new TradingDesk(this);
    return td;
  }
}

请注意,上面的 getter 不是线程安全的。

this施工期间不要逃跑

于 2012-10-31T01:46:11.623 回答