← 中文资源

简体中文版本

仓储模式

仓储为领域对象提供类集合的访问接口,隐藏持久化细节,让领域逻辑不依赖具体数据库或 ORM。

阅读英文原文

概念概述

仓储模式(Repository Pattern)指的是:仓储为领域对象提供类集合的访问接口,隐藏持久化细节,让领域逻辑不依赖具体数据库或 ORM。

从更严格的定义看,The repository pattern mediates between the domain and data mapping layers, exposing an in-memory collection interface for retrieving and storing aggregates while encapsulating query and persistence logic. 该概念在工程实践中的价值,在于它能帮助团队用统一的语言描述一个具体的质量属性或设计约束,从而在评审与协作中减少歧义。

为什么需要它

It is applied in layered and domain-driven designs where the domain should not depend on SQL or an ORM session. 它与 Unit of Work、Publish-Subscribe Messaging、Message Broker 等概念经常一起出现,用于解决相近的工程问题。理解它的适用场景,有助于在多种备选方案之间做出有依据的取舍,而不是凭直觉选择技术方案。

常见误解

  • a repository is the same as a data access object
  • repositories must expose a query builder to be useful

需要避免的反模式

  • returning ORM entities directly into the domain layer
  • creating one repository per table instead of per aggregate

实践要点

  1. By returning domain objects rather than rows or ORM proxies, the repository keeps persistence ignorance, so the domain layer has no compile-time dependency on the database.
  2. Repositories should be defined per aggregate, not per table, because the aggregate is the unit of consistency the domain cares about.
  3. Leaking a query or criteria object through the interface turns the repository back into a data access object and gives callers control over persistence specifics.

参考来源

https://martinfowler.com/eaaCatalog/repository.html