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

后端 未结 7 2361
自闭症患者
自闭症患者 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:22

    Slightly pedantic, but it's not strictly speaking necessary to create one inside the other, if you don't mind a little indirection. They could both be inner classes.

    public class BadlyNamedClass {
        private final User owner;
        private final Inventory inventory;
    
        public BadlyNamedClass() {
            this.owner = new User() {
                ... has access to BadlyNamedClass.this.inventory;
            };
            this.inventory = new Inventory() {
                ... has access to BadlyNamedClass.this.owner;
            };
        }
        ...
    }
    

    Or even:

    public class BadlyNamedClass {
        private final User owner;
        private final Inventory inventory;
    
        public BadlyNamedClass() {
            this.owner = new User(this);
            this.inventory = new Inventory(this);
        }
        public User getOwner() { return owner; }
        public Inventory getInventory() { return inventory; }
        ...
    }
    

提交回复
热议问题