聚合根设计 logo

聚合根设计

Organization
microwind
聚合根设计

聚合的入口点,外部只能通过聚合根访问聚合内部对象,保证数据一致性和业务不变量。

Overview

Publishermicrowind
Repositoryai-skills
Skill name聚合根设计
Stars
93
Forks
25
Bundled files
Instructions only
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by microwind on GitHub. Read the source before you install it.

Installation

Install the 聚合根设计 AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/microwind/ai-skills/tree/main/domain-driven-design/aggregate-root-design
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/microwind/ai-skills.git /tmp/ai-skills
mkdir -p .claude/skills
cp -r /tmp/ai-skills/domain-driven-design/aggregate-root-design .claude/skills/microwind-56
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable 聚合根设计 in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads 聚合根设计 on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so 聚合根设计 is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

聚合根设计 (Aggregate Root Design)

概述

聚合根是聚合的唯一入口,外部对象只能通过聚合根与聚合交互;它持有聚合的全局标识,负责维护聚合的所有业务不变量。

核心规则:

  • 聚合根本身是 Entity,拥有全局唯一标识
  • 外部对象只引用聚合根,不直接引用内部实体或值对象
  • 聚合根负责维护所有跨子对象的业务不变量
  • 仓储以聚合根为单位加载与保存(一次性加载完整聚合)
  • 聚合根负责**产生(raise / record)**领域事件——把"已发生的事实"记入自身;事件的对外发布则由应用服务在事务边界统一完成(或经由 Outbox 投递)
  • 一个事务只修改一个聚合实例
  • 聚合间通过 ID 引用,不通过对象引用

代码示例

java
// ✅ Order 是聚合根,OrderItem 是内部实体
public class Order {  // 聚合根
    private OrderId id;
    private CustomerId customerId;  // 引用其他聚合用 ID
    private List<OrderItem> items = new ArrayList<>();
    private OrderStatus status;
    private Money totalAmount;

    // 所有操作通过聚合根进行
    public void addItem(ProductId productId, Money price, int quantity) {
        if (status != OrderStatus.DRAFT) {
            throw new DomainException("只有草稿订单可以添加商品");
        }
        if (quantity <= 0) {
            throw new DomainException("数量必须为正");
        }
        // 检查不变量:同一商品不能重复添加
        if (items.stream().anyMatch(i -> i.getProductId().equals(productId))) {
            throw new DomainException("商品已存在,请修改数量");
        }
        items.add(new OrderItem(productId, price, quantity));
        recalculateTotal();
    }

    public void removeItem(ProductId productId) {
        items.removeIf(i -> i.getProductId().equals(productId));
        recalculateTotal();
    }

    private void recalculateTotal() {
        this.totalAmount = items.stream()
            .map(OrderItem::subtotal)
            .reduce(Money.ZERO, Money::add);
    }
}

// OrderItem 是内部实体,外部不能直接访问
public class OrderItem {  // 内部实体
    private ProductId productId;
    private Money unitPrice;
    private int quantity;

    Money subtotal() { return unitPrice.multiply(quantity); }
}
python
# ✅ 聚合根设计
class ShoppingCart:  # 聚合根
    def __init__(self, cart_id: str, customer_id: str):
        self.id = cart_id
        self.customer_id = customer_id  # 引用其他聚合用 ID
        self._items: list[CartItem] = []

    def add_item(self, product_id: str, price: Decimal, quantity: int):
        existing = self._find_item(product_id)
        if existing:
            existing.increase_quantity(quantity)
        else:
            self._items.append(CartItem(product_id, price, quantity))

    def checkout(self) -> "Order":
        if not self._items:
            raise DomainError("购物车为空")
        # 聚合根负责创建新聚合
        return Order.create_from_cart(self.customer_id, list(self._items))

    def _find_item(self, product_id: str):
        return next((i for i in self._items if i.product_id == product_id), None)

聚合设计原则

1. 尽量小的聚合
   ❌ 一个聚合包含 Order + Customer + Product + Payment
   ✅ Order 聚合只包含 Order + OrderItems

2. 聚合间通过 ID 引用
   ❌ private Customer customer;  // 对象引用
   ✅ private CustomerId customerId;  // ID 引用

3. 一个事务一个聚合
   ❌ 一个事务修改 Order + Inventory + Payment
   ✅ 一个事务只修改 Order,通过事件通知其他聚合

4. 最终一致性
   聚合内:强一致性(事务保证)
   聚合间:最终一致性(通过事件)

常见误区

❌ 为内部实体单独建仓储——OrderItemRepository、OrderLineRepository → 一聚合一仓储;内部实体通过聚合根加载和保存

❌ 聚合根成为"上帝类"——所有方法都堆在 Order 上,单类逾千行 → 跨聚合的协同抽到领域服务;聚合内的复杂规则抽成规约 / 策略对象

❌ 对外暴露内部可写集合——getItems() 返回可写 List,外部直接增删 → 返回不可变视图(Collections.unmodifiableList),或只暴露查询方法(findItemBySku())

与其他DDD概念的关系

概念关系
聚合聚合根是聚合的入口
实体聚合根本身是实体
领域事件聚合根发布领域事件
仓储仓储按聚合根为单位操作

总结

核心:聚合根是唯一入口,维护一致性,控制所有写操作。

实践:聚合尽量小、通过 ID 引用其他聚合、一个事务一个聚合。

Frequently asked questions

What does the 聚合根设计 AI skill do?

聚合的入口点,外部只能通过聚合根访问聚合内部对象,保证数据一致性和业务不变量。

Why use 聚合根设计 on TypingMind?

Because you install it once and use it with any model. 聚合根设计 is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install 聚合根设计 in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/microwind/ai-skills/tree/main/domain-driven-design/aggregate-root-design. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use 聚合根设计?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with 聚合根设计?

As many as you like. As long as a model supports skills, you can use 聚合根设计 with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the 聚合根设计 AI skill free?

It is published on GitHub by microwind. Check the repository for licensing terms. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇