Easy-Go-Web3
知识图谱Go 教程React Web3智能合约
需求分析系统设计设计模式Go 微服务
项目实战DevOps
Go 生态React 生态智能合约生态Web3 生态AI × Web3工具箱Web3 公司远程Web3求职
🎯 AA 工程师面试手册博客
GitHub
返回微服务模块

领域驱动设计 (DDD)

运用 DDD 思想构建复杂业务系统

1领域模型

领域模型是对业务领域的抽象,包含实体、值对象、聚合等概念。

核心概念: - **实体 (Entity)**:有唯一标识的对象 - **值对象 (Value Object)**:无标识,不可变 - **聚合 (Aggregate)**:一组相关对象的集合 - **聚合根 (Aggregate Root)**:聚合的入口点

go
1// 实体
2type Order struct {
3 ID OrderID
4 Customer CustomerID
5 Items []OrderItem
6 Status OrderStatus
7 CreatedAt time.Time
8}
9
10// 值对象
11type Money struct {
12 Amount decimal.Decimal
13 Currency string
14}
15
16func (m Money) Add(other Money) Money {
17 return Money{
18 Amount: m.Amount.Add(other.Amount),
19 Currency: m.Currency,
20 }
21}

2仓储模式

仓储模式抽象了数据访问层,使领域模型与持久化机制解耦。

go
1// 仓储接口
2type OrderRepository interface {
3 Save(ctx context.Context, order *Order) error
4 FindByID(ctx context.Context, id OrderID) (*Order, error)
5 FindByCustomer(ctx context.Context, customerID CustomerID) ([]*Order, error)
6}
7
8// 实现
9type PostgresOrderRepository struct {
10 db *sql.DB
11}
12
13func (r *PostgresOrderRepository) Save(ctx context.Context, order *Order) error {
14 _, err := r.db.ExecContext(ctx,
15 "INSERT INTO orders (id, customer_id, status) VALUES ($1, $2, $3)",
16 order.ID, order.Customer, order.Status,
17 )
18 return err
19}
上一模块:微服务架构设计下一模块:gRPC 与服务通信
Easy-Go-Web3

构建 Go 后端与 Web3 的学习之路。从基础到进阶,从理论到实践,助你成为全栈区块链开发者。

学习路径

  • 知识图谱
  • Go 教程
  • Go 微服务
  • 面试手册

资源中心

  • 工具箱
  • DevOps 工具
  • Web3 生态
  • 博客

© 2025 Easy-Go-Web3. All rights reserved.

Created withbyhardybao