Medium Programming & OOP OOP Fundamentals
Implement and explain the Singleton design pattern.
Answer
Singleton ensures a class has only one instance with global access. Implementation: private constructor, private static instance, public static getInstance() method. Thread-safe options: synchronized getInstance (slow), eager initialization (simple), double-checked locking (volatile + sync), enum singleton (Java, best practice), static holder class (lazy, thread-safe). Use cases: logging, configuration, connection pools. Criticisms: global state, testing difficulty, hidden dependencies. Consider dependency injection as alternative. Ensure: private constructor, static instance, controlled access.
IIT Certified
Master These Concepts with IIT Certification
175+ hours of industry projects. Get placed at Bosch, Tata Motors, L&T and 500+ companies.
Relevant for Roles
Software Engineer Backend Developer Software Architect