首页 > 解决方案 > Is there good usecases of crossreferenced classes in OOP ? (A class referencing B, B referencing A)

问题描述

I am doing a personal project in Java and I would like to make a really "clean" code and classes design.

I am asking myself if this design is would be OK in this case :

public class Team {
  private String teamName;
  private List<Employee> team;
}

public class Employee {
  private String name;
  private Team parent;
}

I made this design because I can directly retrieve all employees of a given team through Team object but also directly get the linked team of a given employee. But the disadvantage I find is it can create incoherent references.

Is there any "cleaner way" to achieve that ? What questions should I ask whenever I am facing that kind of problematic ?

I know it's a quite generalist question but I have no methodology concerning entities relationship in OOP.

Thanks for any help,

标签: javaoopdesign-patterns

解决方案


有没有“更清洁的方法”来实现这一目标?

示例 1:

常见做法 - 只Team知道它有哪些员工。

public class Team {
  private String teamName;
  private List<Employee> employees;
}

public class Employee {
  private String name;
}

示例 2:

彼此完全分开Team并创建一个新类来处理它们的关系。Employee这样,只有一个真实的地方,如果您愿意,您可以将一名员工分配给多个团队。

public class Team {
  private String teamName;
}

public class Employee {
  private String name;
}

public class Membership {
  private Team team;
  private List<Employee> employees;
}

推荐阅读