关注点分离 logo

关注点分离

Organization
microwind
关注点分离

将程序分解为不同的部分,每个部分处理一个单独的关注点,减少耦合提高内聚。

Overview

Publishermicrowind
Repositoryai-skills
Skill name关注点分离
Stars
93
Forks
25
Bundled files
1
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.

  • 1 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/separation-of-concerns
  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/separation-of-concerns .claude/skills/microwind-50
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.

关注点分离 (Separation of Concerns, SoC)

概述

关注点分离由 Dijkstra 于1974年提出:将系统分解为不同的部分,每个部分解决一个独立的关注点。

核心思想:

  • 每个模块/层/组件只负责一个关注点
  • 不同关注点之间通过明确的接口交互
  • 修改一个关注点不应该影响其他关注点

经典应用:MVC 模式

java
// ✅ 关注点分离:Model-View-Controller

// Model:只关注数据和业务逻辑
public class User {
    private String name;
    private String email;

    public boolean isValid() {
        return name != null && !name.isEmpty()
            && email != null && email.contains("@");
    }
}

// Controller:只关注请求处理和流程协调
public class UserController {
    private final UserService service;
    private final UserView view;

    public Response handleCreate(Request request) {
        User user = service.create(request.getBody());
        return view.render(user);
    }
}

// View:只关注数据展示
public class UserView {
    public Response render(User user) {
        return Response.json(Map.of("name", user.getName()));
    }
}

违反 SoC 的示例

python
# ❌ 混合关注点:业务逻辑 + 数据访问 + 展示
class OrderProcessor:
    def process(self, order_data: dict):
        # 关注点1:数据验证
        if not order_data.get("items"):
            print("错误:订单为空")  # 展示逻辑混入
            return

        # 关注点2:业务逻辑
        total = sum(i["price"] * i["qty"] for i in order_data["items"])
        if total > 10000:
            total *= 0.9

        # 关注点3:数据持久化
        import sqlite3
        conn = sqlite3.connect("orders.db")
        conn.execute("INSERT INTO orders VALUES (?, ?)",
                     (order_data["id"], total))
        conn.commit()

        # 关注点4:通知
        import smtplib
        server = smtplib.SMTP("smtp.example.com")
        server.sendmail("shop@example.com", order_data["email"],
                        f"订单已处理,总计: {total}")

# ✅ 关注点分离
class OrderValidator:
    def validate(self, order_data: dict) -> bool:
        return bool(order_data.get("items"))

class PricingService:
    def calculate(self, items: list) -> float:
        total = sum(i["price"] * i["qty"] for i in items)
        return total * 0.9 if total > 10000 else total

class OrderRepository:
    def save(self, order_id: str, total: float):
        # 数据库操作
        pass

class NotificationService:
    def notify(self, email: str, message: str):
        # 邮件发送
        pass

class OrderProcessor:
    def __init__(self, validator, pricing, repo, notifier):
        self.validator = validator
        self.pricing = pricing
        self.repo = repo
        self.notifier = notifier

    def process(self, order_data: dict):
        if not self.validator.validate(order_data):
            raise ValueError("无效订单")
        total = self.pricing.calculate(order_data["items"])
        self.repo.save(order_data["id"], total)
        self.notifier.notify(order_data["email"], f"总计: {total}")

分层架构中的 SoC

┌─────────────────────────┐
│   Presentation Layer    │  关注点:用户交互、数据展示
├─────────────────────────┤
│   Application Layer     │  关注点:用例编排、事务管理
├─────────────────────────┤
│   Domain Layer          │  关注点:业务规则、领域逻辑
├─────────────────────────┤
│   Infrastructure Layer  │  关注点:数据库、外部服务、框架
└─────────────────────────┘

规则:上层依赖下层,下层不知道上层的存在

前端中的 SoC

typescript
// ❌ 关注点混合
function UserProfile() {
    const [user, setUser] = useState(null);

    useEffect(() => {
        // 数据获取逻辑混在组件中
        fetch('/api/users/1')
            .then(res => res.json())
            .then(data => {
                // 业务逻辑混在组件中
                data.fullName = `${data.firstName} ${data.lastName}`;
                data.age = new Date().getFullYear() - data.birthYear;
                setUser(data);
            });
    }, []);

    // 展示逻辑
    return <div>{user?.fullName}, {user?.age}岁</div>;
}

// ✅ 关注点分离
// hooks/useUser.ts - 数据获取
function useUser(id: string) {
    const [user, setUser] = useState(null);
    useEffect(() => {
        fetch(`/api/users/${id}`).then(r => r.json()).then(setUser);
    }, [id]);
    return user;
}

// utils/userUtils.ts - 业务逻辑
function formatUser(user: RawUser): DisplayUser {
    return {
        fullName: `${user.firstName} ${user.lastName}`,
        age: new Date().getFullYear() - user.birthYear,
    };
}

// components/UserProfile.tsx - 展示
function UserProfile({ id }: { id: string }) {
    const user = useUser(id);
    if (!user) return <Loading />;
    const display = formatUser(user);
    return <div>{display.fullName}, {display.age}岁</div>;
}

最佳实践

常见的关注点划分

关注点职责示例
业务逻辑核心规则价格计算、权限验证
数据访问持久化Repository、DAO
展示逻辑UI渲染View、Template
基础设施技术支撑日志、缓存、消息队列
横切关注跨层需求认证、审计、事务

分离信号

需要分离的信号:
□ 一个类/方法混合了多种不同的操作(数据库 + 业务 + 展示)
□ 修改展示逻辑时需要修改业务代码
□ 同样的业务逻辑在 API 和 CLI 中重复
□ 单元测试需要启动数据库或 Web 服务器

与其他原则的关系

原则关系
SRPSRP 是类级别的 SoC
ISPISP 是接口级别的 SoC
DIPDIP 通过抽象实现层间分离
封装封装隐藏内部实现,支持 SoC

总结

SoC 核心:一个模块只处理一个关注点。

实践要点:

  • 按关注点划分模块、层、组件
  • 通过接口定义关注点之间的边界
  • 横切关注点用 AOP 或中间件处理
  • 修改一个关注点不应该影响其他关注点

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/separation-of-concerns. 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 👇