# 四层架构设计

![图 9](/files/C7ULfWyTVxCO6ry88L8f)

传统的三层架构实际上我们能够很明显的发现，我们的数据库将会做为架构起点，我们会从数据库层面开始分析以及设计，但是我们的DDD他的重点其实不在数据库，而是在领域模型，我们会将领域模型做为我们的分析基点，向上进行衍生。进而进行分层设计。

1. User Interface，用户界面层，负责向用户显示信息和解释用户命令。
   1. 业务/界面接口
   2. 对外的model
2. Application为应用层，定义软件要完成的任务，并且指挥表达领域概念的对象来解决问题。
   1. 线程调度
   2. 应用服务
   3. 与实体无关的业务逻辑
3. Domain领域层，或者说是模型层。负责表达业务概念，业务状态信息以及业务规则，也就是我们的领域模型。
   1. 业务概念抽象
   2. 业务规则
   3. 领域模型
4. Infrastructure基础设施层，应用层传递消息，为领域层提供持久化机制，为用户界面层绘制屏幕组件，等等。基础设施层还能够通过架构框架来支持四个层次间的交互模式。
   1. 交互层次，可以被任何层调用
   2. 提供持久化机制
   3. 为用户界面提供基础绘制组件

## 严格分层架构和松散分层架构

四层架构设计是松散分层架构，其上层可以直接访问下面的任何一层：UserIntefce可以直接访问Domain，任何一层可以直接访问Infrastructure层。相反的，严格分层架构，其上层只能访问与之仅连的一层，不可以跨层访问。

## 四层架构代码结构对照表

```java
├─com.yangsx95
│    │
│    ├─apis   API接口层
│    │    ├─model        视图模型,数据模型定义 vo/dto（大多数情況是一样的）
│    │    ├─assembler    装配器，实现模型转换 apiModel => domainModel  （在Java项目里可以使用MapStruct为此层提供功能）
│    │    └─controller   控制器，对外提供（Restful）接口
│    │
│    ├─application   应用层
│    │    ├─service  应用服务，非核心服务
│    │    ├─task     任务定义，协调领域模型
│    │    └─***      others
│    │
│    ├─domain   领域层
│    │    ├─common       公共代码抽取，限于领域层有效
│    │    ├─events       领域事件
│    │    ├─model        领域模型
│    │    │    ├─dict    领域划分的模块，可理解为子域划分
│    │    │    │    ├─DictVo.java       领域值对象
│    │    │    │    ├─DictEntity.java   领域实体，充血的领域模型，如本身的CRUD操作在此处
│    │    │    │    ├─DictAgg.java      领域聚合，通常表现为实体的聚合，需要有聚合根
│    │    │    │    └─DictService.java  领域服务，不能归与上述模型，如分页条件查询等可写在此处
│    │    │    ├─xxx
│    │    │    │    ├─xxxEntity.java
│    │    │    │    ├─bbbAgg.java
│    │    │    │    └─cccAgg.java
│    │    ├─service      领域服务类，一些不能归属某个具体领域模型的行为
│    │    └─factory      工厂类，负责复杂领域对象创建，封装细节
│    │
│    ├─infrastructure  基础设施层
│    │    ├─persistent   持久化机制
│    │    │    ├─po           持久化对象
│    │    │    └─repository   仓储类，持久化接口&实现，可与ORM映射框架结合
│    │    ├─general      通用技术支持，向其他层输出通用服务
│    │    │    ├─config       配置类
│    │    │    ├─toolkit      工具类
│    │    │    └─common       基础公共模块等
│    │
│    └─resources
│        ├─statics  静态资源
│        ├─template 系统页面
│        └─application.yml   全局配置文件

```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://yangsx95.gitbook.io/notes/architect/ddd-ling-yu-qu-dong-she-ji/si-ceng-jia-gou-she-ji.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
