I haven't found a good answer to my question regarding the best way of handling multiple objects in Java. I have seen a couple of questions here on StackOverflow, but I'm not satisfied with the answers that they have.
Let's say I have a Player
class:
public class Player
{
private String nickname;
private long maxHealth;
private long health;
public Player(String nickname, long maxHealth, long health)
{
this.nickname = nickname;
this.maxHealth = maxHealth;
this.health = health;
}
public String getNickname()
{
return nickname;
}
public void setNickname(String nickname)
{
this.nickname = nickname;
}
public long getMaxHealth()
{
return maxHealth;
}
public void setMaxHealth(long maxHealth)
{
this.maxHealth = maxHealth;
}
public long getHealth()
{
return health;
}
public void setHealth(long health)
{
this.health = health;
}
}
Let's also say I have a game where there are multiple players in one game, depending on how many users are online. It would be necessary to store all the players somewhere, we want the information like health to be saved and retrieved later on, changed and saved again. With my current knowledge I would create something like this to do the job:
public class PlayerManager
{
private static final PlayerManager SINGLETON = new PlayerManager();
private final Set<Player> players;
private PlayerManager() {
this.players = new HashSet<>();
}
public static PlayerManager getSingleton()
{
return SINGLETON;
}
public void addPlayer(Player p)
{
players.add(p);
}
public void removePlayer(Player p)
{
players.remove(p);
}
public boolean exists(String nickname)
{
return players.stream().filter(p -> p.getNickname().equalsIgnoreCase(nickname)).count() == 1;
}
... getPlayer(String nickname), ...
}
My whole project would be able to use the PlayerManager
singleton to add, remove and retrieve players. It would work, but I have the feeling that this is not the best way of doing this. What is the best way to store and retrieve objects?