java - 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,
解决方案
有没有“更清洁的方法”来实现这一目标?
示例 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;
}
推荐阅读
- excel - 为什么我的 ComboBox 只显示第一个结果?
- dji-sdk - 使用 Zenmuse 云台连接器为激光扫描仪提供 12V 电源
- javascript - jQuery 键盘输入
- matlab - 从图中提取 x 和 y 截距
- javascript - React 组件在网页中是空白的
- python - PySpark AttributeError:类型对象“ALS”没有属性“trainImplicit”
- c - OpenGL计算着色器不改变缓冲区
- javascript - 字符串 JavaScript 中的常见字符数
- html - 子文件夹的 Html 文件路径
- python - Flask 没有看到在乘客中设置的环境变量(Dreamhost 托管)