Singleton Design Pattern in Java with Code & Explanation

🚀 Singleton Design Pattern in Java – With Complete Code & Explanation Today I solved a HackerRank challenge on the Singleton Pattern — a very important concept in object-oriented design. 🎯 What is Singleton? 👉 Ensures that a class has only one instance and provides a global access point to it. 🛠️ Complete Code with Line-by-Line Explanation: import java.util.Scanner; import java.lang.reflect.*; // Singleton class class Singleton { // Step 1: Create a single static instance of the class public static final Singleton singleton = new Singleton(); // Step 2: Public variable to store string public String str; // Step 3: Private constructor (prevents object creation from outside) private Singleton() { } // Step 4: Public method to return the single instance public static Singleton getSingleInstance() { return singleton; } } // Main class public class Main { public static void main(String args[]) throws Exception { // Scanner to take input Scanner sc = new Scanner(System.in); // Step 5: Get the same instance twice Singleton s1 = Singleton.getSingleInstance(); // first reference Singleton s2 = Singleton.getSingleInstance(); // second reference // Step 6: Check both references point to same object assert (s1 == s2); // true means Singleton works // Step 7: Verify constructor is private using Reflection Class c = s1.getClass(); Constructor[] allConstructors = c.getDeclaredConstructors(); assert allConstructors.length == 1; for (Constructor ctor : allConstructors) { // Modifier 2 = private if (ctor.getModifiers() != 2 || !ctor.toString().equals("private Singleton()")) { System.out.println("Wrong class!"); } } // Step 8: Take input string String str = sc.nextLine(); // Step 9: Assign value to singleton object s1.str = str; s2.str = str; // both refer to same object // Step 10: Print output System.out.println("Hello I am a singleton! Let me say " + str + " to you"); } } 💡 Key Takeaways: ✔ Only one object is created ✔ Constructor is private ✔ Access through static method ✔ Memory efficient & widely used 🔥 Where is it used? 👉 Logging systems 👉 Configuration management 👉 Database connections #Java #DesignPatterns #SingletonPattern #OOP #HackerRank #CodingPractice #JavaDeveloper #LearningJourney

To view or add a comment, sign in

Explore content categories