OO design and circular dependencies

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-03 05:50:45

You can break the circular dependency by adding guards to check if the team still has the player / the player is still in the team. For example:

In class Team:

public void removePlayer(Player player) {
    if (players.contains(player))
    {
        players.remove(player);
        player.leaveTeam();
        // Do other admin work when a player leaves
    }
}

In class Player:

public void leaveTeam() {
    if (team != null)
    {
        team.removePlayer(this);
        team = null;
        // Do some more player stuff..
    }
}

Ben,

I would start by asking if a player can (logically, legally) remove himself from the team. I would say the player object doesn't know what team he's in (!), he is part of a team. So, delete Player#leaveTeam() and make all team changes occur through the Team#removePlayer() method.

In the case where you only have a player and need to remove it from its team, then you could have a static lookup method on Team public static Team findTeam( Player player ) ...

I know this is less satisfying and natural than a Player#leaveTeam() method, but in my experience you can still have a meaningful domain model.

2 way references (Parent -> Child and Child-> Parent) are often fraught with other things, say Garbage Collection, maintaining the "referential integrity", etc.

Design is a compromise!

Gaurav Saxena

Idea is to do domain-related stuff in different methods which do not call each other but does domain related stuff for their own object, i.e. team's method does it for team and player's method does it for player

public class Team {

    private List<Player> players;

    public void removePlayer(Player player) {
        removePlayerFromTeam(player);
        player.removeFromTeam();
    }
    public void removePlayerFromTeam(Player player) {
        players.remove(player);
        //domain stuff
    }
}

public class Player {
    private Team team;

    public void removeFromTeam() {
         team = null;
        //domain stuff
    }
    public void leaveTeam() {
        team.removePlayerFromTeam(this);
        removeFromTeam();
    }

}
Vlad Gudim
public void removePlayer(Player player) {
    if (players.contains(player)) {
        players.remove(player);
        player.leaveTeam();
    }
}

Ditto inside leaveTeam.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!