首页 > 解决方案 > 在干净的架构中正确管理存储库

问题描述

我是实施干净架构的新手,虽然我真的很喜欢这个概念,但是,当我想到存储库实施时,我总是不确定。

例如:我总能找到这样的图表 使用实体的 repo 接口

在这些图中,存储库接口使用实体,而实体对任何事情一无所知。问题是我认为实体意识到存储库接口可能更有用。我认为它不会违反控制反转原则,因为它们只是接口而不是实现。

一个例子(不是真正的代码或语言,因为在这种情况下语言并不重要):

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 接口使用实体而不是其他方式?有什么优点?

我知道这很多,所以提前非常感谢

标签: clean-architecture

解决方案


如何将这些方法放在我的实体中?

您不需要将这些方法放在您的实体中。

用例查询存储库,存储库应该返回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();
    }
}

易于测试并与存储库分离。


推荐阅读