clean-architecture - 在干净的架构中正确管理存储库
问题描述
我是实施干净架构的新手,虽然我真的很喜欢这个概念,但是,当我想到存储库实施时,我总是不确定。
在这些图中,存储库接口使用实体,而实体对任何事情一无所知。问题是我认为实体意识到存储库接口可能更有用。我认为它不会违反控制反转原则,因为它们只是接口而不是实现。
一个例子(不是真正的代码或语言,因为在这种情况下语言并不重要):
Class StudentEntity:
important method: getMathGrade
Class MathClassroomEntity:
constructor(repository){
this.repo = repository
}
important method: getStudents(){
this.repo.getStudents()
}
important method: getAverageGrade(){
students = this.getStudents()
sum = 0
foreach student in students:
sum = student.getMathGrade()
return sum/students.length
}
如您所见,一个实体中的许多重要业务逻辑都与其他实体相关。
如果实体对 repos (至少接口)一无所知。
如何将这些方法放在我的实体中?
我应该让我的实体抽象吗?我认为不是那么漂亮
我应该把这个业务逻辑放在我的用例中吗?听起来更糟
为什么他们让 repo 接口使用实体而不是其他方式?有什么优点?
我知道这很多,所以提前非常感谢
解决方案
如何将这些方法放在我的实体中?
您不需要将这些方法放在您的实体中。
用例查询存储库,存储库应该返回MathClassroomEntity
应该只包含学生的存储库。
class RepositoryImpl implements Repository {
public MathClassroom getMathClassroom(){
return new MathClassroom(getStudents);
}
private List<Student> getStudents(){
return .....;
}
}
因此 MathClassroom 将只知道学生
public class MathClassroom {
private List<Student> students;
public MathClassroom(List<Student> students){
this.students = students;
}
public double getAverageGrade(){
double sum = 0;
for(Student student : students){
sum += student.getMathGrade()
}
return sum / students.size();
}
}
易于测试并与存储库分离。
推荐阅读
- python-3.x - python:显示列表中的唯一元素
- javascript - 如何禁用 Telerik 验证?
- html - 使用python创建html文档
- javascript - 如何在 c3 分组条形图上固定 Y 轴的位置?
- java - 错误:用于编码 windows-1251 的不可映射字符 (0x98)
- pentaho - 如何在pentaho pdi的目标表中检查数据是否存在
- html - 使用弹性框时如何在属性周围垂直应用空间?
- python - windows 10更改用户文件夹名称后如何恢复系统
- c# - 正确的过载选择
- python - 如何在树莓派 3 中安装 pymysql sing raspbian os