singleton-pattern
БесплатноБез исполняемых скриптовНе проверенTeaches the singleton pattern for managing a single shared instance. Use when exactly one instance of a class or object is needed to coordinate actions across…
от PatternsDev★ 261 звезда на GitHubОб этом скилле
Singleton Pattern
Table of Contents
Singletons are classes which can be instantiated once, and can be accessed globally. This single instance can be shared throughout our application, which makes Singletons great for managing global state in an application.
When to Use
- Use this when you need exactly one instance of a class shared across the entire application
- This is helpful for managing global state, configuration, or shared resources
When NOT to Use
- When you need multiple instances of a class — singletons enforce a single shared instance by design
- When it introduces hidden global state coupling that makes testing and reasoning about code harder
- When dependency injection or module-scoped variables achieve the same result with better testability
Instructions
- Ensure only one instance can be created by checking for an existing instance in the constructor
- Use
Object.freeze()on the exported instance to prevent accidental modifications - In JavaScript, prefer simple object literals or modules over class-based singletons when possible
- In React, prefer state management tools (Redux, Context) over Singletons for global state
- Be aware that Singletons can make testing more difficult due to shared mutable state
Details
First, let's take a look at what a singleton can look like using an ES2015 class. For this example, we're going to build a Counter class that has:
- a
getInstancemethod that returns the value of the instance - a
getCountmethod that returns the current value of thecountervariable - an
incrementmethod that increments the value ofcounterby one - a
decrementmethod that decrements the value ofcounterby one
let counter = 0;
class Counter {
getInstance() {
return this;
}
getCount() {
return counter;
}
increment() {
return ++counter;
}
decrement() {
return --counter;
}
}
However, this class doesn't meet the criteria for a Singleton! A Singleton should only be able to get instantiated once. Currently, we can create multiple instances of the Counter class.
let counter = 0;
class Counter {
getInstance() {
return this;
}
getCount() {
return counter;
}
increment() {
return ++counter;
}
decrement() {
return --counter;
}
}
const counter1 = new Counter();
const counter2 = new Counter();
console.log(counter1.getInstance() === counter2.getInstance()); // false
By calling the new method twice, we just set counter1 and counter2 equal to different instances. The values returned by the getInstance method on counter1 and counter2 effectively returned references to different instances: they aren't strictly equal!
Let's make sure that only one instance of the Counter class can be created.
One way to make sure that only one instance can be created, is by creating a variable called instance. In the constructor of Counter, we can set instance equal to a reference to the instance when a new instance is created. We can prevent new instantiations by checking if the instance variable already had a value. If that's the case, an instance already exists. This shouldn't happen: an error should get thrown to let the user know.
let instance;
let counter = 0;
class Counter {
constructor() {
if (instance) {
throw new Error("You can only create one instance!");
}
instance = this;
}
getInstance() {
return this;
}
getCount() {
return counter;
}
increment() {
return ++counter;
}
decrement() {
return --counter;
}
}
const counter1 = new Counter();
const counter2 = new Counter();
// Error: You can only create one instance!
Perfect! We aren't able to create multiple instances anymore.
Let's export the Counter instance from the counter.js file. But before doing so, we should freeze the instance as well. The Object.freeze method makes sure that consuming code cannot modify the Singleton. Properties on the frozen instance cannot be added or modified, which reduces the risk of accidentally overwriting the values on the Singleton.
let instance;
let counter = 0;
class Counter {
constructor() {
if (instance) {
throw new Error("You can only create one instance!");
}
instance = this;
}
getInstance() {
return this;
}
getCount() {
return counter;
}
increment() {
return ++counter;
}
decrement() {
return --counter;
}
}
const singletonCounter = Object.freeze(new Counter());
export default singletonCounter;
Consider an application that implements the Counter example with the following files:
counter.js: contains theCounterclass, and exports aCounterinstance as its default exportindex.js: loads theredButton.jsandblueButton.jsmodules- `
Установить singleton-pattern в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл singleton-pattern?
Teaches the singleton pattern for managing a single shared instance. Use when exactly one instance of a class or object is needed to coordinate actions across your application.
Как установить скилл singleton-pattern?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл singleton-pattern запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic