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

后端 未结 7 2484
自闭症患者
自闭症患者 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条回答
  •  萌比男神i
    2021-02-13 05:26

    B: "Inventory created by the User is our last hope".
    Y: "No, there is another."

    If you abstract the references to a third party, you can control the relationship therein.

    For example.

    public class User
    {
        private final String identifier;  // uniquely identifies this User instance.
    
        public User(final String myIdentifier)
        {
            identifier = myIdentifier;
    
            InventoryReferencer.registerBlammoUser(identifier); // Register the user with the Inventory referencer.
        }
    
        public Inventory getInventory()
        {
            return InventoryReferencer.getInventoryForUser(identifier);
        }
    }
    
    public interface Inventory // Bam!
    {
        ... nothing special.
    }
    
    // Assuming that the Inventory only makes sence in the context of a User (i.e. User must own Inventory).
    public class InventoryReferencer
    {
        private static final Map referenceMap = new HashMap();
    
        private InventoryReferencer()
        {
            throw ... some exception - helps limit instantiation.
        }
    
        public static void registerBlammoUser(final String identifier)
        {
            InventoryBlammo blammo = new InventoryBlammo();
            referenceMap.add(indentifier, blammo);
        }
    
        public static void registerKapowUser(final String identifier)
        {
            InventoryBlammo kapow = new InventoryKapow();
            referenceMap.add(indentifier, kapow);
        }
    
        public static Inentory getInfentoryForUser(final String identifier)
        {
            return referenceMap.get(identifier);
        }
    }
    
    // Maybe package access constructors.
    public class InventoryBlammo implements Inventory
    {
        // a Blammo style inventory.
    }
    
    public class InventoryKapow implements Inventory
    {
        // a Kapow style inventory.
    }
    

提交回复
热议问题