正确管理干净架构中的存储库

时间:2019-07-29 04:06:06

标签: clean-architecture

尽管我真的很喜欢这个概念,但是我对实现干净的体系结构还是陌生的,但是当我想到存储库实现时,我总是不确定。

例如:我总是找到这样的图 repo interface using entity (对不起,我没有信誉发布图片:-c)

在这些图中,存储库接口使用实体,而实体对此一无所知。我认为对于实体而言,意识到存储库接口可能更有用。我认为这不会违反控制原理,因为它们只是接口而不是实现。

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

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()
    }

如您所见,一个实体中的许多重要业务逻辑与其他实体有关。

如果实体对回购协议一无所知(至少是接口)。

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

我应该使我的实体抽象吗?我觉得不是很漂亮

我应该在用例中使用这种业务逻辑吗?听起来更糟

为什么它们使repo接口使用实体而不是其他方式?有什么优势?

我知道很多,所以在此先谢谢

1 个答案:

答案 0 :(得分:2)

  

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

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

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

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