我没有找到关于在Java中处理多个对象的最佳方法的问题的一个很好的答案。我在StackOverflow上看到了几个问题,但我对他们的答案并不满意。
假设我有一个Player
课程:
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;
}
}
我们还说我有一个游戏,其中一个游戏中有多个玩家,具体取决于在线用户数量。有必要将所有玩家存储在某个地方,我们希望稍后保存和检索健康等信息,更改并再次保存。根据我目前的知识,我会创建这样的东西来完成这项工作:
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), ...
}
我的整个项目都可以使用PlayerManager
单例来添加,删除和检索玩家。它会起作用,但我觉得这不是最好的方法。存储和检索对象的最佳方法是什么?