分层架构原则 logo

分层架构原则

Organization
microwind
分层架构原则

将系统划分为职责明确的层次,每层只与相邻层交互,实现关注点分离和独立变化。

Overview

Publishermicrowind
Repositoryai-skills
Skill name分层架构原则
Stars
93
Forks
25
Bundled files
2
LicenseMIT
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.

  • 2 bundled files

    Scripts, templates, and references the model can read while it works. Files are read-only and never executed.

  • 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/design-principles/layered-architecture-principle
  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/design-principles/layered-architecture-principle .claude/skills/microwind-43
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.

分层架构原则 (Layered Architecture Principle)

概述

分层架构是最经典的软件架构模式:将系统按职责划分为水平层次,每层为上层提供服务,同时使用下层的服务。

核心规则:

  • 每层职责单一且明确
  • 上层依赖下层,下层不知道上层存在
  • 跨层调用必须经过中间层(严格分层)或可跳层(松散分层)
  • 同层内的组件可以互相调用

经典四层架构

┌─────────────────────────────┐
│    Presentation Layer       │  UI、API 接口、控制器
│    表示层                    │  接收输入,返回响应
├─────────────────────────────┤
│    Application Layer        │  用例编排、事务管理
│    应用层                    │  协调领域对象完成业务流程
├─────────────────────────────┤
│    Domain Layer             │  业务规则、领域模型
│    领域层                    │  核心业务逻辑,不依赖任何技术细节
├─────────────────────────────┤
│    Infrastructure Layer     │  数据库、消息队列、外部API
│    基础设施层                │  技术实现细节
└─────────────────────────────┘

代码示例

java
// ✅ 清晰的分层

// 表示层:只负责 HTTP 请求/响应
@RestController
public class OrderController {
    private final OrderApplicationService appService;

    @PostMapping("/orders")
    public ResponseEntity<OrderDTO> create(@RequestBody CreateOrderRequest req) {
        OrderDTO result = appService.createOrder(req);
        return ResponseEntity.created(URI.create("/orders/" + result.getId())).body(result);
    }
}

// 应用层:编排业务流程
@Service
@Transactional
public class OrderApplicationService {
    private final OrderRepository orderRepo;
    private final InventoryService inventoryService;

    public OrderDTO createOrder(CreateOrderRequest req) {
        inventoryService.reserve(req.getItems());
        Order order = Order.create(req.getCustomerId(), req.getItems());
        orderRepo.save(order);
        return OrderDTO.from(order);
    }
}

// 领域层:纯业务逻辑
public class Order {
    private OrderId id;
    private List<OrderItem> items;
    private OrderStatus status;

    public static Order create(CustomerId customerId, List<ItemRequest> items) {
        // 业务规则验证
        if (items.isEmpty()) throw new DomainException("订单不能为空");
        return new Order(OrderId.generate(), customerId, items);
    }

    public void confirm() {
        if (status != OrderStatus.PENDING) {
            throw new DomainException("只有待处理订单可以确认");
        }
        this.status = OrderStatus.CONFIRMED;
    }
}

// 基础设施层:技术实现
@Repository
public class JpaOrderRepository implements OrderRepository {
    private final JpaEntityManager em;

    public void save(Order order) {
        em.persist(OrderEntity.fromDomain(order));
    }
}
python
# ✅ Python 分层示例

# 表示层
@app.route("/orders", methods=["POST"])
def create_order():
    data = request.get_json()
    result = order_app_service.create_order(data)
    return jsonify(result), 201

# 应用层
class OrderApplicationService:
    def __init__(self, order_repo, inventory_service):
        self.order_repo = order_repo
        self.inventory_service = inventory_service

    def create_order(self, data: dict) -> dict:
        self.inventory_service.reserve(data["items"])
        order = Order.create(data["customer_id"], data["items"])
        self.order_repo.save(order)
        return order.to_dict()

# 领域层
class Order:
    @staticmethod
    def create(customer_id: str, items: list) -> "Order":
        if not items:
            raise DomainError("订单不能为空")
        return Order(id=uuid4(), customer_id=customer_id, items=items)

# 基础设施层
class SqlOrderRepository:
    def save(self, order: Order):
        db.session.add(OrderModel.from_domain(order))
        db.session.commit()

违反分层的典型问题

java
// ❌ 表示层直接访问数据库
@RestController
public class OrderController {
    @Autowired
    private JdbcTemplate jdbc;  // 跨层依赖!

    @GetMapping("/orders/{id}")
    public Map<String, Object> getOrder(@PathVariable Long id) {
        return jdbc.queryForMap("SELECT * FROM orders WHERE id = ?", id);
    }
}

// ❌ 领域层依赖框架
public class Order {
    @Autowired  // 领域对象不应该依赖 Spring
    private EmailService emailService;

    public void confirm() {
        this.status = CONFIRMED;
        emailService.send(this.customerEmail, "订单已确认");  // 领域层不应处理通知
    }
}

分层变体

模式特点适用场景
严格分层只能调用直接下层大型企业系统
松散分层可以跳层调用中小型项目
六边形架构端口+适配器需要多种外部集成
洋葱架构依赖指向中心DDD 项目

最佳实践

  1. 领域层零依赖 - 不依赖框架、数据库、HTTP
  2. 层间通过接口通信 - 上层定义接口,下层实现
  3. DTO 隔离 - 每层有自己的数据传输对象,不跨层传递领域对象
  4. 依赖方向一致 - 依赖只能从上到下(或从外到内)

与其他原则的关系

原则关系
关注点分离分层是 SoC 最经典的实现
DIP通过 DIP 实现下层不依赖上层
封装每层封装自己的实现细节

总结

分层架构核心:按职责划分层次,依赖方向从上到下。

实践要点:

  • 表示层:接收请求、返回响应
  • 应用层:编排流程、管理事务
  • 领域层:核心业务规则,零框架依赖
  • 基础设施层:数据库、外部服务等技术实现

Bundled files

The model reads these on demand while the skill is loaded. They are exposed as readable files and are never executed.

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/design-principles/layered-architecture-principle. TypingMind reads its SKILL.md and bundles its files 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?

Yes. It is published on GitHub by microwind under the MIT license. 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 👇