domain-model-boundaries-mapper

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Domain Model & Boundaries Mapper

领域模型与边界映射工具

Map domain boundaries and ownership using Domain-Driven Design.
运用领域驱动设计(Domain-Driven Design)映射领域边界与所有权。

Domain Map Template

领域图模板

markdown
undefined
markdown
undefined

Domain Map: E-Commerce Platform

Domain Map: E-Commerce Platform

Bounded Contexts

Bounded Contexts

1. Customer Management

1. Customer Management

Core Domain: User accounts, profiles, preferences Owner: Customer Team Ubiquitous Language:
  • Customer: Registered user with account
  • Profile: Customer personal information
  • Preferences: User settings and choices
Entities:
  • Customer (id, email, name)
  • Address (id, customer_id, street, city)
  • PaymentMethod (id, customer_id, type, token)
Bounded Context Diagram:

┌─────────────────────────────┐
│ Customer Management │
│ ┌─────────┐ ┌──────────┐ │
│ │Customer │ │ Address │ │
│ └─────────┘ └──────────┘ │
│ ┌─────────────────────┐ │
│ │ Payment Method │ │
│ └─────────────────────┘ │
└─────────────────────────────┘
Core Domain: User accounts, profiles, preferences Owner: Customer Team Ubiquitous Language:
  • Customer: Registered user with account
  • Profile: Customer personal information
  • Preferences: User settings and choices
Entities:
  • Customer (id, email, name)
  • Address (id, customer_id, street, city)
  • PaymentMethod (id, customer_id, type, token)
Bounded Context Diagram:

┌─────────────────────────────┐
│ Customer Management │
│ ┌─────────┐ ┌──────────┐ │
│ │Customer │ │ Address │ │
│ └─────────┘ └──────────┘ │
│ ┌─────────────────────┐ │
│ │ Payment Method │ │
│ └─────────────────────┘ │
└─────────────────────────────┘

2. Order Management

2. 订单管理

Core Domain: Order processing, fulfillment Owner: Orders Team Ubiquitous Language:
  • Order: Purchase request with line items
  • LineItem: Product quantity in order
  • Fulfillment: Physical delivery of order
Entities:
  • Order (id, customer_id, status, total)
  • LineItem (id, order_id, product_id, quantity)
  • Shipment (id, order_id, tracking_number)
核心领域: 订单处理、履约交付 负责团队: 订单团队 Ubiquitous Language:
  • Order:包含商品明细的采购请求
  • LineItem:订单中的商品数量
  • Fulfillment:订单的实物配送
实体:
  • Order (id, customer_id, status, total)
  • LineItem (id, order_id, product_id, quantity)
  • Shipment (id, order_id, tracking_number)

3. Product Catalog

3. 产品目录

Core Domain: Product information, inventory Owner: Catalog Team Ubiquitous Language:
  • Product: Sellable item
  • SKU: Stock keeping unit
  • Inventory: Available stock
Entities:
  • Product (id, name, price, description)
  • Inventory (sku, quantity, warehouse_id)
核心领域: 产品信息、库存管理 负责团队: 目录团队 Ubiquitous Language:
  • Product:可售卖商品
  • SKU:库存单位
  • Inventory:可用库存
实体:
  • Product (id, name, price, description)
  • Inventory (sku, quantity, warehouse_id)

Context Relationships

上下文关系


Customer Management ──────▶ Order Management
(customer_id)

Product Catalog ──────▶ Order Management
(product_id)

Order Management ──────▶ Fulfillment
(order events)

Customer Management ──────▶ Order Management
(customer_id)

Product Catalog ──────▶ Order Management
(product_id)

Order Management ──────▶ Fulfillment
(order events)

Anti-Corruption Layers

防腐层

Order Management → Customer Management

订单管理 → 客户管理

Problem: Orders need customer data but shouldn't depend on Customer domain model
Solution: Customer Adapter
typescript
// Order domain's view of customer
interface CustomerForOrder {
  id: string;
  shippingAddress: Address;
  billingAddress: Address;
}

// Adapter translates Customer domain to Order domain
class CustomerAdapter {
  async getCustomerForOrder(customerId: string): Promise<CustomerForOrder> {
    const customer = await customerService.getCustomer(customerId);
    return {
      id: customer.id,
      shippingAddress: this.toOrderAddress(customer.defaultShippingAddress),
      billingAddress: this.toOrderAddress(customer.defaultBillingAddress),
    };
  }
}
问题: 订单需要客户数据,但不应依赖客户领域模型 解决方案: 客户适配器
typescript
// Order domain's view of customer
interface CustomerForOrder {
  id: string;
  shippingAddress: Address;
  billingAddress: Address;
}

// Adapter translates Customer domain to Order domain
class CustomerAdapter {
  async getCustomerForOrder(customerId: string): Promise<CustomerForOrder> {
    const customer = await customerService.getCustomer(customerId);
    return {
      id: customer.id,
      shippingAddress: this.toOrderAddress(customer.defaultShippingAddress),
      billingAddress: this.toOrderAddress(customer.defaultBillingAddress),
    };
  }
}

Dependency Map

依赖关系图

┌──────────────┐
│   Customer   │
└──────┬───────┘
┌──────────────┐      ┌────────────┐
│    Orders    │─────▶│  Products  │
└──────┬───────┘      └────────────┘
┌──────────────┐
│ Fulfillment  │
└──────────────┘
Dependency Rules:
  • Customer has no dependencies
  • Orders depends on Customer (read) and Products (read)
  • Fulfillment depends on Orders (events)
┌──────────────┐
│   Customer   │
└──────┬───────┘
┌──────────────┐      ┌────────────┐
│    Orders    │─────▶│  Products  │
└──────┬───────┘      └────────────┘
┌──────────────┐
│ Fulfillment  │
└──────────────┘
依赖规则:
  • 客户领域无依赖
  • 订单领域依赖客户领域(只读)和产品领域(只读)
  • 履约领域依赖订单领域(事件)

Interface Contracts

接口契约

Customer Management → Orders

客户管理 → 订单管理

typescript
// Public interface exposed by Customer domain
interface CustomerService {
  getCustomer(id: string): Promise<Customer>;
  getCustomerAddresses(id: string): Promise<Address[]>;
}

// Events published
interface CustomerUpdated {
  customerId: string;
  email: string;
  name: string;
}
typescript
// Public interface exposed by Customer domain
interface CustomerService {
  getCustomer(id: string): Promise<Customer>;
  getCustomerAddresses(id: string): Promise<Address[]>;
}

// Events published
interface CustomerUpdated {
  customerId: string;
  email: string;
  name: string;
}

Product Catalog → Orders

产品目录 → 订单管理

typescript
interface ProductService {
  getProduct(id: string): Promise<Product>;
  checkAvailability(sku: string, quantity: number): Promise<boolean>;
  reserveInventory(items: ReservationRequest[]): Promise<Reservation>;
}
typescript
interface ProductService {
  getProduct(id: string): Promise<Product>;
  checkAvailability(sku: string, quantity: number): Promise<boolean>;
  reserveInventory(items: ReservationRequest[]): Promise<Reservation>;
}

Refactor Recommendations

重构建议

Problem 1: Tight Coupling

问题1:紧耦合

Current: Orders directly queries Customer database Issue: Breaks bounded context, creates coupling Recommendation: Use Customer API instead
typescript
// ❌ Before: Direct database access
const customer = await db.customers.findById(customerId);

// ✅ After: API call through adapter
const customer = await customerAdapter.getCustomerForOrder(customerId);
现状: 订单直接查询客户数据库 问题: 破坏限界上下文,造成耦合 建议: 使用客户API替代
typescript
// ❌ Before: Direct database access
const customer = await db.customers.findById(customerId);

// ✅ After: API call through adapter
const customer = await customerAdapter.getCustomerForOrder(customerId);

Problem 2: Shared Models

问题2:共享模型

Current: Same
User
model used across contexts Issue: Changes in one context affect others Recommendation: Separate models per context
typescript
// Customer context
interface Customer {
  id: string;
  email: string;
  profile: CustomerProfile;
  preferences: CustomerPreferences;
}

// Order context (different model!)
interface OrderCustomer {
  id: string;
  shippingAddress: Address;
  billingAddress: Address;
}
现状: 多个上下文使用相同的
User
模型 问题: 一个上下文的变更会影响其他上下文 建议: 为每个上下文分离模型
typescript
// Customer context
interface Customer {
  id: string;
  email: string;
  profile: CustomerProfile;
  preferences: CustomerPreferences;
}

// Order context (different model!)
interface OrderCustomer {
  id: string;
  shippingAddress: Address;
  billingAddress: Address;
}

Problem 3: God Service

问题3:上帝服务

Current:
OrderService
handles orders, inventory, payments, shipping Issue: Single service owns too much Recommendation: Extract bounded contexts
  • OrderService: Order lifecycle
  • InventoryService: Stock management
  • PaymentService: Payment processing
  • FulfillmentService: Shipping
现状:
OrderService
处理订单、库存、支付、配送 问题: 单个服务职责过多 建议: 拆分限界上下文
  • OrderService:订单生命周期管理
  • InventoryService:库存管理
  • PaymentService:支付处理
  • FulfillmentService:配送管理

Strategic Design Patterns

战略设计模式

Pattern 1: Shared Kernel

模式1:共享内核

When: Two contexts must share some code Example: Common value objects (Money, Address)
typescript
// Shared kernel (minimal!)
class Money {
  constructor(public amount: number, public currency: string) {}
}
适用场景: 两个上下文必须共享部分代码 示例: 通用值对象(Money、Address)
typescript
// Shared kernel (minimal!)
class Money {
  constructor(public amount: number, public currency: string) {}
}

Pattern 2: Customer/Supplier

模式2:客户/供应商

When: One context depends on another Example: Orders (customer) depends on Products (supplier)
  • Supplier defines interface
  • Customer adapts to their needs
适用场景: 一个上下文依赖另一个上下文 示例: 订单(客户)依赖产品(供应商)
  • 供应商定义接口
  • 客户适配自身需求

Pattern 3: Published Language

模式3:发布语言

When: Many contexts need same data Example: Product events
typescript
interface ProductCreated {
  productId: string;
  name: string;
  price: Money;
  publishedAt: Date;
}
适用场景: 多个上下文需要相同数据 示例: 产品事件
typescript
interface ProductCreated {
  productId: string;
  name: string;
  price: Money;
  publishedAt: Date;
}

Migration Strategy

迁移策略

Phase 1: Identify Boundaries

阶段1:识别边界

  • Map existing code to domains
  • Identify coupling points
  • Document dependencies
  • 将现有代码映射到各个领域
  • 识别耦合点
  • 记录依赖关系

Phase 2: Define Interfaces

阶段2:定义接口

  • Design APIs between contexts
  • Create adapter layers
  • Define event contracts
  • 设计上下文间的API
  • 创建适配器层
  • 定义事件契约

Phase 3: Decouple

阶段3:解耦

  • Replace direct DB access with APIs
  • Introduce anti-corruption layers
  • Separate models per context
  • 用API替代直接数据库访问
  • 引入防腐层
  • 为每个上下文分离模型

Phase 4: Extract Services (optional)

阶段4:提取服务(可选)

  • Move contexts to separate services
  • Implement API gateways
  • Set up event bus
  • 将上下文迁移至独立服务
  • 实现API网关
  • 搭建事件总线

Best Practices

最佳实践

  1. Ubiquitous language: Same terms in code and domain
  2. Bounded contexts: Clear boundaries, separate models
  3. Context maps: Document relationships
  4. Anti-corruption layers: Protect domain integrity
  5. Event-driven: Loose coupling via events
  6. Separate databases: Context owns its data
  1. Ubiquitous Language: 代码与领域使用统一术语
  2. Bounded Contexts: 清晰的边界,独立的模型
  3. 上下文映射: 记录上下文间的关系
  4. 防腐层: 保护领域完整性
  5. 事件驱动: 通过事件实现松耦合
  6. 独立数据库: 每个上下文拥有自身数据

Output Checklist

输出检查清单

  • Bounded contexts identified (3-7)
  • Core domain vs supporting domains
  • Ubiquitous language defined per context
  • Entity/aggregate definitions
  • Context relationship diagram
  • Dependency map
  • Interface contracts defined
  • Anti-corruption layers designed
  • Refactor recommendations
  • Migration strategy
  • 已识别限界上下文(3-7个)
  • 区分核心领域与支撑领域
  • 为每个上下文定义Ubiquitous Language
  • 定义实体/聚合根
  • 上下文关系图
  • 依赖关系图
  • 定义接口契约
  • 设计防腐层
  • 重构建议
  • 迁移策略