简体   繁体   中英

Java- Creating Consistency Between Two Variable in Separate Classes

I have three classes- User, Floor, and Directory.

Directory holds/creates multiple static Floor objects.

Each User object, along with other information, needs to know what Floor they're on.

Each Floor, along with other information, needs to know what Users are one them.

I would like to do something like this:

public class Directory{

  public static Floor floor1 = new Floor(3);
  public static Floor floor2 = new Floor(3);

  class Floor{

     private User[] users;

     private Floor(int allowedUsers){
        users = users[4];
     }

     public boolean addUser(User toAdd){
        // if there is a free slot on floor, add User
        for(int i = 0; i < users.length; i++){
           if(users[i] == null){
              users[i] = toAdd;
              return true;
           }
        }
        return false;
     }
           ....(other Floor methods)....
  }

}

With a User class like this:

public class User{

  private Floor floor;

  public boolean setFloor(Floor floor){
     // some code here
     // returns true if floor successfully added
  }

     ....(other User methods)....
}

The issue: I want to ensure that the information held by my User and Floor objects are always consistent with each other so that all the Users know what Floor they are on and all the Floors know what Users are on them. To do this the setters need to make a call to each other. How do I do this without creating an infinite loop? This seems like a common enough problem that I assume there is a standard format for it but I don't know what it is.

One option is to have a separate class to represent the locations of users -- the relationship between floor and users.

That class could be Directory itself, or a new class, that Directory holds an instance of.

public class LocationMap {
    private Map<Floor,Set<User>> = new HashMap<>(); 
    private Map<User,Floor> = new HashMap<>();

    public @CheckForNull Floor getFloorOf( @Nonnull User user ) { ... }

    public @CheckForNull Set<User> getUsersOn( @Nonnull Floor floor ) { ... }

    ...
}

The collections above require equals() and hashCode() be defined on Floor and User. Alternatively, you could use floor IDs and user IDs.

If necessary, the Floors and Users can share a reference to the LocationMap. Alternatively, if only code external to these classes needs to locate a user, it can do so directly through the LocationMap.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM