Frage

I have member.objects that are painters, carpenters and TeamLeads which can have other TeamLeads, painters or carpenters under them. Is there a way to connect them so that I can getTeamLeads.team and also have the ability to see who is working under their TeamLeads.team. I understand how to do it with a database but wanted to see if composition or aggregation would handle a 1:m relationship and if there is an example somewhere that I could see. Would it require maybe a Team.class to link everyone or can it be handled by local references and I just can't find any examples.

War es hilfreich?

Lösung

As i see it you can do this with a private collection that can be managed by modifiers which also mantain reverse relationship something like this:

public class TeamMember {
    private TeamMember leader;
    private Set<TeamMember> teamMembers= new HashSet<TeamMember>();
    public Set<TeamMember> getTeamMembers(){
        return new HashSet<TeamMember>(teamMembers);
    }
    public void addTeamMember(TeamMember member){
        if(member.leader!=null){
            member.leader.removeTeamMember(member);
        }
        member.leader=this;
        teamMembers.add(member);
    }
    public void removeTeamMember(TeamMember member){
        member.leader=null;
        teamMembers.remove(member);
    }
    public TeamMember getLeader(){
        return leader;
    }
}

Since you dont have public setters for teamMembers or leader the only way to change leader or teamMembers is by using the addTeamMember and removeTeamMember methods so you have the bidirectional relationship mantained by these methods.

I wish this may help.

Andere Tipps

So it sounds like you have some a method with this sort of signature to retrieve the list of TeamLead:

public List<TeamLead> getTeamLeads()

And from there, you want to get the members of each team, your TeamLead class would look something like this:

public class TeamLead {
    private final List<Person> team = new ArrayList<Person> ();

    // You can of course populate this list however is best for your code
    public void addTeamMember(Person p) {
        team.add(p);
    }

    public List<Person> getTeam() {
        return team;
    }

    // more code...
}

Where Person is the base class for Painter, Carpenter, and TeamLead - there are other ways to do this without a class hierarchy, but I'll stick to this for easier explanation for now.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top