封装原则 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/encapsulation-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/encapsulation-principle .claude/skills/microwind-40
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.

封装原则 (Encapsulation Principle)

概述

封装是面向对象设计的基石:隐藏对象内部状态和实现细节,只通过受控的接口与外部交互。

核心思想:

  • 数据和操作数据的方法绑定在一起
  • 内部实现对外不可见
  • 通过公共方法控制访问和修改
  • 保护对象不变量不被外部破坏

代码示例

java
// ❌ 缺乏封装:内部状态暴露
public class BankAccount {
    public double balance;      // 公开字段
    public List<Transaction> transactions;  // 公开集合

    // 任何人都可以直接修改余额
    // account.balance = -1000;  合法但错误!
}

// ✅ 良好封装
public class BankAccount {
    private double balance;
    private final List<Transaction> transactions = new ArrayList<>();

    public BankAccount(double initialBalance) {
        if (initialBalance < 0) throw new IllegalArgumentException("初始余额不能为负");
        this.balance = initialBalance;
    }

    public void deposit(double amount) {
        if (amount <= 0) throw new IllegalArgumentException("存款金额必须为正");
        this.balance += amount;
        transactions.add(new Transaction(TransactionType.DEPOSIT, amount));
    }

    public void withdraw(double amount) {
        if (amount <= 0) throw new IllegalArgumentException("取款金额必须为正");
        if (amount > balance) throw new InsufficientFundsException();
        this.balance -= amount;
        transactions.add(new Transaction(TransactionType.WITHDRAWAL, amount));
    }

    public double getBalance() { return balance; }

    public List<Transaction> getTransactions() {
        return Collections.unmodifiableList(transactions);  // 返回不可变视图
    }
}
python
# ✅ Python 封装
class ShoppingCart:
    def __init__(self):
        self._items: list[CartItem] = []  # 受保护

    def add_item(self, product, quantity: int):
        if quantity <= 0:
            raise ValueError("数量必须为正")
        existing = self._find_item(product.id)
        if existing:
            existing.quantity += quantity
        else:
            self._items.append(CartItem(product, quantity))

    def remove_item(self, product_id: str):
        self._items = [i for i in self._items if i.product.id != product_id]

    @property
    def total(self) -> float:
        return sum(i.subtotal for i in self._items)

    @property
    def items(self) -> tuple:
        return tuple(self._items)  # 返回不可变副本

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

封装层次

层次说明示例
字段封装私有字段 + getter/setterprivate + getXxx()
行为封装数据和行为在一起account.withdraw()
实现封装隐藏算法细节sort() 不暴露排序算法
类型封装隐藏具体类型返回接口而非实现类
模块封装隐藏内部类只导出公共 API

常见封装破坏

java
// ❌ 1. 返回内部可变集合的引用
public List<Item> getItems() {
    return this.items;  // 外部可以直接修改!
}

// ✅ 返回不可变副本
public List<Item> getItems() {
    return Collections.unmodifiableList(this.items);
}

// ❌ 2. getter/setter 全部暴露 = 没有封装
public class User {
    private String name;
    private String email;
    private int age;
    // 为每个字段都生成 getter/setter = 等于公开字段
}

// ✅ 只暴露必要的操作
public class User {
    public void updateProfile(String name, String email) {
        validateEmail(email);
        this.name = name;
        this.email = email;
    }
}

// ❌ 3. 通过参数暴露内部结构
public void processOrder(Map<String, Object> orderData) {
    // 调用方需要知道 map 的 key 结构
}

// ✅ 使用类型化参数
public void processOrder(OrderRequest request) {
    // 结构明确,编译时检查
}

最佳实践

  1. 默认 private - 字段和方法默认私有,按需开放
  2. 不可变优先 - 能用 final/readonly 就用
  3. 防御性拷贝 - 返回集合或可变对象时返回副本
  4. 告诉不要问 - 让对象执行操作,而非获取数据后外部操作

与其他原则的关系

原则关系
最少知识封装支撑迪米特法则
SRP封装帮助划定职责边界
OCP封装变化点使扩展更安全

总结

封装核心:隐藏实现,暴露接口,保护不变量。

实践:字段私有、行为内聚、返回不可变视图、用类型代替裸数据。

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/encapsulation-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 👇