Setter 方法相互设置字段 class

Setter methods set fields in each others class

我有两个 类,玩家和团队。一个玩家有一个团队字段,一个团队有一个 playerList 字段,包含该团队中的玩家。玩家加入队伍时,玩家的team字段要设置为该队伍,队伍的playerList中要添加加入的玩家对象。到目前为止,这是我所拥有的,但这不是很递归吗?我怎么解决这个问题?下面提供了示例代码。


public class Team {

   private ArrayList<Player> playerList;
   
   public void addPlayer(Player player){
      playerList.add(player);
      player.joinTeam(this);
   }

}

public class Player {
   
   private Team team;
   
   public void joinTeam(Team team) {
      this.team = team;
      team.addPlayer(this)
   }

}


好吧,为了使您的代码正常工作,您应该从方法 joinTeam() 中删除 team.addPlayer(this)。但是现在你只是为你的属性设置一个值,所以它应该是 setTeam().

public class Team {

   private ArrayList<Player> playerList;
   
   public void addPlayer(Player player){
      playerList.add(player);
      player.joinTeam(this);
   }

}

public class Player {
   
   private Team team;
   
   public void setTeam(Team team) {
      this.team = team;
   }

}

原则上,对于特定类型的操作,您实际上应该只有一个函数。如果你想添加一个球员到一个球队,像

public class Team {

   private ArrayList<Player> playerList;
   
   public void addPlayer(Player player) {
      playerList.add(player);
      player.setTeam(this);
   }
}

public class Player {
   
   private Team team;
   
   public void setTeam(Team team) {
      this.team = team;
   }
}

会更适合您的任务。您只需调用一种方法 (addPlayer),您希望发生的两种操作都会发生。