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

后端 未结 7 2359
自闭症患者
自闭症患者 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:40
    class User {
        private final Inventory inventory;
        User (/*whatever additional args are needed to construct the inventory*/) {
            //populate user fields
            inventory = new Inventory(this);
        }
    }
    
    class Inventory {
        private final User owner;
        Inventory (User own) {
            owner = own;
        }
    }
    

    That's the best I can think of. Maybe there's a better pattern.

    0 讨论(0)
提交回复
热议问题