Any nice way to make two immutable objects refer to eachother?

后端 未结 7 2363
自闭症患者
自闭症患者 2021-02-13 04:53

Take these two Java classes:

class User {
   final Inventory inventory;
   User (Inventory inv) {
       inventory = inv;
   }
}

class Inventory {
   final User         


        
7条回答
  •  一向
    一向 (楼主)
    2021-02-13 05:16

    This is one "solution", though the loss of one final is inconvenient.

    class User {
       Inventory inventory;
       User () { }
       // make sure this setter is only callable from where it should be,
       // and is called only once at construction time
       setInventory(inv) {
           if (inventory != null) throw new IllegalStateException();
           inventory = inv;
       }
    }
    
    class Inventory {
       final User owner;
       Inventory (User own) {
           owner = own;
       }
    }
    

提交回复
热议问题