← 中文资源

简体中文版本

分层架构

分层架构把代码组织为依赖向下的水平层,使职责分离显式化,但也可能产生技术泄漏与贫血的领域模型。

阅读英文原文

概念概述

分层架构(Layered Architecture)指的是:分层架构把代码组织为依赖向下的水平层,使职责分离显式化,但也可能产生技术泄漏与贫血的领域模型。

从更严格的定义看,Layered architecture is a structural pattern that partitions a system into logical layers, such as presentation, application, domain, and infrastructure, where each layer depends only on the layers beneath it. 该概念在工程实践中的价值,在于它能帮助团队用统一的语言描述一个具体的质量属性或设计约束,从而在评审与协作中减少歧义。

为什么需要它

It is the default shape of many enterprise applications and a starting point for teams that need clear module boundaries. 它与 Onion Architecture、Clean Architecture、Domain-Driven Design 等概念经常一起出现,用于解决相近的工程问题。理解它的适用场景,有助于在多种备选方案之间做出有依据的取舍,而不是凭直觉选择技术方案。

常见误解

  • layers must be deployed as separate services
  • strict layering automatically yields a good domain model

需要避免的反模式

  • letting the presentation layer call the database directly
  • putting business rules in controllers or repositories

实践要点

  1. The rule that a layer may call only lower layers keeps dependencies acyclic, so a change in the domain does not ripple upward into infrastructure.
  2. Technology concerns can leak through the layers unless the domain stays free of framework types, which is where the style is frequently compromised.
  3. Because layers are logical rather than physical, all of them usually run in one process, which keeps deployment simple but limits independent scaling.

参考来源

https://martinfowler.com/bliki/PresentationDomainDataLayering.html