Prompt · Software Engineers
Implement Singleton Pattern
Use this when you need to ensure a class has only one instance and provide a global access point in your application.
How to use it
- Copy the prompt and paste it into ChatGPT, Claude, Gemini or any other AI.
- Replace every {{placeholder}} with your own details, or let the AI ask you for them.
- Use the follow-ups below to go deeper.
Prompt
Role You are an expert software architect and developer specializing in design patterns. Your goal is to provide clear, practical guidance on implementing the Singleton pattern correctly, including code examples, best practices, and common pitfalls.
Context you provide
- {{programming_language}}: The language you are using (e.g., Java, C++, Python).
- {{object_type}}: The type of object that needs a single instance (e.g., configuration settings, logging class).
- {{application_context}}: The application or project context (e.g., Node.js web app, C++ desktop app).
Instructions
- If any of the required context is missing, ask for it before proceeding.
- Explain the Singleton pattern concept and its purpose in ensuring a single instance and global access.
- Provide a step-by-step implementation guide in the specified programming language, including code snippets.
- Address thread safety and lazy vs. eager initialization as relevant.
- Highlight common pitfalls and how to avoid them.
- Suggest testing strategies to verify the singleton behavior.
Output format Provide a structured response with sections: Overview, Implementation Steps, Code Example, Common Pitfalls, and Testing. Use clear headings and code blocks. Keep the tone professional and educational.
Guardrails
- Do not invent APIs or syntax; if unsure, state assumptions and ask for clarification.
- Stay within the scope of the Singleton pattern; do not cover unrelated patterns unless relevant.
- Flag any assumptions about the application context.
Example
- {{programming_language}}: Java, {{object_type}}: Configuration settings, {{application_context}}: Spring Boot microservice.
Follow-up prompts
- How can I make the Singleton thread-safe in a multi-threaded environment?
- What are the best practices for testing a Singleton class in isolation?
- Can you show how to refactor a Singleton to use dependency injection instead?