command-pattern — скилл для Claude Code: что делает и как установить
Обучает агента паттерну «Команда» для JavaScript и TypeScript. Помогает разделить вызов операции и её выполнение, настроить очередь задач или историю отмены.
npx skills add PatternsDev/skills --skill command-pattern -a claude-codeЧто делает command-pattern
Скилл настраивает правила работы с кодом в файлах **/*.js и **/*.ts. Он предписывает выносить прямые вызовы методов сервиса в отдельные объекты-команды, передаваемые в единый метод execute. Вместо жёсткой сцепки с методами конкретного менеджера код опирается на обёртки команд.
Такой подход нужен для реализации отложенного запуска, очередей или механизмов отмены и повтора действий (undo/redo). Однако для простых сценариев без очередей и логирования паттерн создаёт лишний шаблонный код, поэтому архитектуру не стоит усложнять на пустом месте.
Какие задачи решает
- развязать вызов операций и логику их выполнения в JS и TS
- подготовить архитектуру для механизма отмены и повтора действий
- организовать очередь задач с отложенным запуском
- избавиться от жёсткой зависимости компонентов от методов сервиса
Примеры запросов агенту
- Перепиши класс OrderManager на паттерн Command, чтобы вызовы шли через метод execute
- Помоги разделить вызов методов и их реализацию в файле cart.ts с помощью command pattern
- Спроектируй команды с методом execute для очереди задач в JavaScript
Как установить command-pattern
1Через Skills CLI (Vercel)
npx skills add PatternsDev/skills --skill command-pattern -a claude-code2Вручную: положить файлы
~/.claude/skills/command-pattern/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/command-pattern/
1Через Skills CLI (Vercel)
npx skills add PatternsDev/skills --skill command-pattern -a codex2Вручную: положить файлы
.agents/skills/command-pattern/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add PatternsDev/skills --skill command-pattern -a cursor2Вручную: положить файлы
.cursor/skills/command-pattern/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install PatternsDev/skills command-pattern2Вручную: положить файлы
.github/skills/command-pattern/SKILL.md1Через Skills CLI (Vercel)
npx skills add PatternsDev/skills --skill command-pattern -a gemini-cli2Командой платформы
gemini skills install https://github.com/PatternsDev/skills --path javascript/command-patternВручную: положить файлы
.devin/skills/command-pattern/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add PatternsDev/skills --skill command-pattern -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Из того же набора44
Похожие
Рядом в теме «Языки программирования»
Все скиллы по теме «Языки программирования» →Вопросы о command-pattern
Как установить command-pattern в Claude Code?
Выполните в терминале команду npx skills add PatternsDev/skills --skill command-pattern -a claude-code.
Зачем нужен скилл command-pattern?
Он задаёт модели правила проектирования, когда требуется отделить вызов действия от объекта его исполнения, например для задач в очереди или сценариев undo/redo.
Когда не стоит применять этот паттерн?
Паттерн не нужен для простых разовых операций, если не требуется вести лог, делать отмену действий или ставить команды в очередь. В таких случаях прямого вызова функций достаточно, а команды добавят лишний бойлерплейт.
Исходный текст
SKILL.md · MIT
---
name: command-pattern
description: Teaches the command pattern for decoupling task execution from invocation. Use when you need undo/redo functionality, queued operations, or want to decouple the object that invokes an operation from the one that performs it.
paths:
- "**/*.js"
- "**/*.ts"
license: MIT
metadata:
author: patterns.dev
version: "1.1"
related_skills:
- "module-pattern"
- "singleton-pattern"
---
# Command Pattern
With the **Command Pattern**, we can _decouple_ objects that execute a certain task from the object that calls the method.
Let's say we have an online food delivery platform. Users can place, track, and cancel orders.
## When to Use
- Use this when you need to decouple the object invoking an operation from the object performing it
- This is helpful when commands need a certain lifespan or should be queued and executed at specific times
## When NOT to Use
- For simple one-off operations that don't need undo/redo, queuing, or logging
- When direct function calls are clear enough and the extra abstraction adds complexity without benefit
- When the system has few operations and the command infrastructure would be over-engineering
## Instructions
- Create a Command class with an `execute` method that encapsulates the action
- Replace direct method calls with command objects passed to a single `execute` method on the manager
- Use this pattern sparingly as it can add unnecessary boilerplate in simpler JavaScript applications
## Details
```js
class OrderManager {
constructor() {
this.orders = []
}
placeOrder(order, id) {
this.orders.push(id)
return `You have successfully ordered ${order} (${id})`;
}
trackOrder(id) {
return `Your order ${id} will arrive in 20 minutes.`
}
cancelOrder(id) {
this.orders = this.orders.filter(order => order !== id)
return `You have canceled your order ${id}`
}
}
```
On the `OrderManager` class, we have access to the `placeOrder`, `trackOrder` and `cancelOrder` methods. It would be totally valid JavaScript to just use these methods directly!
```js
const manager = new OrderManager();
manager.placeOrder("Pad Thai", "1234");
manager.trackOrder("1234");
manager.cancelOrder("1234");
```
However, there are downsides to invoking the methods directly on the `manager` instance. It could happen that we decide to rename certain methods later on, or the functionality of the methods change.
Say that instead of calling it `placeOrder`, we now rename it to `addOrder`! This would mean that we would have to make sure that we don't call the `placeOrder` method anywhere in our codebase, which could be very tricky in larger applications. Instead, we want to decouple the methods from the `manager` object, and create separate command functions for each command!
Let's refactor the `OrderManager` class: instead of having the `placeOrder`, `cancelOrder` and `trackOrder` methods, it will have one single method: `execute`. This method will execute any command it's given.
Each command should have access to the `orders` of the manager, which we'll pass as its first argument.
```js
class OrderManager {
constructor() {
this.orders = [];
}
execute(command, ...args) {
return command.execute(this.orders, ...args);
}
}
```
We need to create three `Command`s for the order manager:
- `PlaceOrderCommand`
- `CancelOrderCommand`
- `TrackOrderCommand`
```js
class Command {
constructor(execute) {
this.execute = execute;
}
}
function PlaceOrderCommand(order, id) {
return new Command((orders) => {
orders.push(id);
return `You have successfully ordered ${order} (${id})`;
});
}
function CancelOrderCommand(id) {
return new Command((orders) => {
const index = orders.indexOf(id);
if (index > -1) orders.splice(index, 1);
return `You have canceled your order ${id}`;
});
}
function TrackOrderCommand(id) {
return new Command(() => `Your order ${id} will arrive in 20 minutes.`);
}
```
Perfect! Instead of having the methods directly coupled to the `OrderManager` instance, they're now separate, decoupled functions that we can invoke through the `execute` method that's available on the `OrderManager`.
### Pros
The command pattern allows us to decouple methods from the object that executes the operation. It gives you more control if you're dealing with commands that have a certain lifespan, or commands that should be queued and executed at specific times.
### Cons
The use cases for the command pattern are quite limited, and often adds unnecessary boilerplate to an application.
## Source
- [patterns.dev/vanilla/command-pattern](https://patterns.dev/vanilla/command-pattern)
### References
- [Command Design Pattern](https://sourcemaking.com/design_patterns/command) - SourceMaking
- [Command Pattern](https://refactoring.guru/design-patterns/command) - Refactoring Guru
- [Command Pattern](https://www.carloscaballero.io/design-patterns-command/) - Carlos Caballero
© patterns.dev · MIT · PatternsDev/skills