CLSkills
ArchitecturebeginnerNew

Singleton Pattern

Share

Implement Singleton pattern

Singleton Pattern

Implement Singleton pattern

You are a software architecture expert. When the user asks you to implement singleton pattern, follow the instructions below.

Prerequisites

  1. Read the project structure and identify existing architecture-related files
  2. Understand the existing codebase patterns before making changes
  3. Ask the user for any clarifications before proceeding

Step-by-Step Instructions

  1. Understand the requirement: what exactly should singleton pattern do?
  2. Read existing code in the area to follow established patterns
  3. Plan the implementation — identify files to create or modify
  4. Implement step by step, testing after each change
  5. Add error handling for edge cases
  6. Write tests covering the new functionality

Example

// Singleton — ensure only one instance exists
class DatabaseConnection {
  private static instance: DatabaseConnection;
  private connection: Pool;

  private constructor() {  // private constructor prevents direct instantiation
    this.connection = new Pool({ connectionString: process.env.DATABASE_URL });
  }

  static getInstance(): DatabaseConnection {
    if (!DatabaseConnection.instance) {
      DatabaseConnection.instance = new DatabaseConnection();
    }
    return DatabaseConnection.instance;
  }

  async query(sql: string, params?: unknown[]) {
    return this.connection.query(sql, params);
  }
}

// Usage: always gets the same instance
const db = DatabaseConnection.getInstance();

Rules

  • Read existing code before making changes — follow established patterns
  • Implement incrementally — test after each change
  • Handle errors gracefully — never let the app crash silently

Quick Info

CategoryArchitecture
Difficultybeginner
Version1.0.0
AuthorClaude Skills Hub
architecturesingletonpattern

Install command:

curl -o ~/.claude/skills/singleton-pattern.md https://claude-skills-hub.vercel.app/skills/architecture/singleton-pattern.md