domain-driven-design

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Domain-Driven Design Tactical Patterns

Domain-Driven Design(DDD)战术模式

Model complex business domains with entities, value objects, and bounded contexts.
使用Entity(实体)、Value Object(值对象)和Bounded Context(限界上下文)对复杂业务领域进行建模。

Overview

概览

  • Modeling complex business logic
  • Separating domain from infrastructure
  • Establishing clear boundaries between subdomains
  • Building rich domain models with behavior
  • Implementing ubiquitous language in code
  • 对复杂业务逻辑进行建模
  • 领域层与基础设施层解耦
  • 明确子领域之间的边界
  • 构建具备业务行为的富领域模型
  • 在代码中实现统一语言(Ubiquitous Language)

Building Blocks Overview

核心构件概览

┌─────────────────────────────────────────────────────────────┐
│                    DDD Building Blocks                       │
├─────────────────────────────────────────────────────────────┤
│  ENTITIES           VALUE OBJECTS        AGGREGATES         │
│  Order (has ID)     Money (no ID)        [Order]→Items      │
│                                                              │
│  DOMAIN SERVICES    REPOSITORIES         DOMAIN EVENTS      │
│  PricingService     IOrderRepository     OrderSubmitted     │
│                                                              │
│  FACTORIES          SPECIFICATIONS       MODULES            │
│  OrderFactory       OverdueOrderSpec     orders/, payments/ │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│                    DDD Building Blocks                       │
├─────────────────────────────────────────────────────────────┤
│  ENTITIES           VALUE OBJECTS        AGGREGATES         │
│  Order (has ID)     Money (no ID)        [Order]→Items      │
│                                                              │
│  DOMAIN SERVICES    REPOSITORIES         DOMAIN EVENTS      │
│  PricingService     IOrderRepository     OrderSubmitted     │
│                                                              │
│  FACTORIES          SPECIFICATIONS       MODULES            │
│  OrderFactory       OverdueOrderSpec     orders/, payments/ │
└─────────────────────────────────────────────────────────────┘

Quick Reference

速查指南

Entity (Has Identity)

Entity(具备唯一标识)

python
from dataclasses import dataclass, field
from uuid import UUID
from uuid_utils import uuid7

@dataclass
class Order:
    """Entity: Has identity, mutable state, lifecycle."""
    id: UUID = field(default_factory=uuid7)
    customer_id: UUID = field(default=None)
    status: str = "draft"

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Order):
            return NotImplemented
        return self.id == other.id  # Identity equality

    def __hash__(self) -> int:
        return hash(self.id)
See entities-value-objects.md for complete patterns.
python
from dataclasses import dataclass, field
from uuid import UUID
from uuid_utils import uuid7

@dataclass
class Order:
    """Entity: 具备唯一标识、可变状态和生命周期。"""
    id: UUID = field(default_factory=uuid7)
    customer_id: UUID = field(default=None)
    status: str = "draft"

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Order):
            return NotImplemented
        return self.id == other.id  # 基于标识判断相等性

    def __hash__(self) -> int:
        return hash(self.id)
完整模式请参考 entities-value-objects.md

Value Object (Immutable)

Value Object(不可变)

python
from dataclasses import dataclass
from decimal import Decimal

@dataclass(frozen=True)  # MUST be frozen!
class Money:
    """Value Object: Defined by attributes, not identity."""
    amount: Decimal
    currency: str

    def __add__(self, other: "Money") -> "Money":
        if self.currency != other.currency:
            raise ValueError("Cannot add different currencies")
        return Money(self.amount + other.amount, self.currency)
See entities-value-objects.md for Address, DateRange examples.
python
from dataclasses import dataclass
from decimal import Decimal

@dataclass(frozen=True)  # 必须设为不可变!
class Money:
    """Value Object: 通过属性而非唯一标识定义。"""
    amount: Decimal
    currency: str

    def __add__(self, other: "Money") -> "Money":
        if self.currency != other.currency:
            raise ValueError("无法对不同货币进行加法运算")
        return Money(self.amount + other.amount, self.currency)
地址、日期范围等示例请参考 entities-value-objects.md

Key Decisions

关键决策建议

DecisionRecommendation
Entity vs VOHas unique ID + lifecycle? Entity. Otherwise VO
Entity equalityBy ID, not attributes
Value object mutabilityAlways immutable (
frozen=True
)
Repository scopeOne per aggregate root
Domain eventsCollect in entity, publish after persist
Context boundariesBy business capability, not technical
决策项建议
Entity vs VO具备唯一ID和生命周期?使用Entity。否则使用VO
Entity相等性判断基于ID,而非属性
值对象可变性始终设为不可变(
frozen=True
仓储作用范围每个聚合根对应一个仓储
领域事件在Entity中收集事件,持久化后发布
上下文边界基于业务能力划分,而非技术层面

Anti-Patterns (FORBIDDEN)

反模式(禁止使用)

python
undefined
python
undefined

NEVER have anemic domain models (data-only classes)

绝对不要使用贫血领域模型(仅包含数据的类)

@dataclass class Order: id: UUID items: list # WRONG - no behavior!
@dataclass class Order: id: UUID items: list # 错误 - 无任何业务行为!

NEVER leak infrastructure into domain

绝对不要将基础设施层逻辑泄露到领域层

class Order: def save(self, session: Session): # WRONG - knows about DB!
class Order: def save(self, session: Session): # 错误 - 依赖数据库会话!

NEVER use mutable value objects

绝对不要使用可变的值对象

@dataclass # WRONG - missing frozen=True class Money: amount: Decimal
@dataclass # 错误 - 缺少frozen=True class Money: amount: Decimal

NEVER have repositories return ORM models

绝对不要让仓储返回ORM模型

async def get(self, id: UUID) -> OrderModel: # WRONG - return domain!
undefined
async def get(self, id: UUID) -> OrderModel: # 错误 - 应返回领域模型!
undefined

Related Skills

相关技能

  • aggregate-patterns
    - Deep dive on aggregate design
  • distributed-locks
    - Cross-aggregate coordination
  • database-schema-designer
    - Schema design for DDD
  • aggregate-patterns
    - 聚合设计深度解析
  • distributed-locks
    - 跨聚合协调
  • database-schema-designer
    - 适配DDD的数据库Schema设计

References

参考资料

  • Entities & Value Objects - Full patterns
  • Repositories - Repository pattern implementation
  • Domain Events - Event collection and publishing
  • Bounded Contexts - Context mapping and ACL
  • Entities & Value Objects - 完整模式说明
  • Repositories - 仓储模式实现
  • Domain Events - 事件收集与发布
  • Bounded Contexts - 上下文映射与ACL(防腐层)

Capability Details

能力详情

entities

entities

Keywords: entity, identity, lifecycle, mutable, domain object Solves: Model entities in Python, identity equality, adding behavior
关键词: entity、唯一标识、生命周期、可变、领域对象 解决问题: 在Python中建模Entity,实现基于标识的相等性,为模型添加业务行为

value-objects

value-objects

Keywords: value object, immutable, frozen, dataclass, structural equality Solves: Create immutable value objects, when to use VO vs entity
关键词: value object、不可变、frozen、dataclass、结构相等性 解决问题: 创建不可变值对象,判断何时使用VO而非Entity

domain-services

domain-services

Keywords: domain service, business logic, cross-aggregate, stateless Solves: When to use domain service, logic spanning aggregates
关键词: domain service、业务逻辑、跨聚合、无状态 解决问题: 判断何时使用领域服务,处理跨聚合的业务逻辑

repositories

repositories

Keywords: repository, persistence, collection, IRepository, protocol Solves: Implement repository pattern, abstract DB access, ORM mapping
关键词: repository、持久化、集合、IRepository、协议 解决问题: 实现仓储模式,抽象数据库访问,处理ORM映射

bounded-contexts

bounded-contexts

Keywords: bounded context, context map, ACL, subdomain, ubiquitous language Solves: Define bounded contexts, integrate with ACL, context relationships
关键词: bounded context、上下文映射、ACL、子领域、统一语言 解决问题: 定义限界上下文,通过ACL实现集成,管理上下文关系