From acc59661a24e148ea33abaefff06d978da98466a Mon Sep 17 00:00:00 2001 From: Manoj kumar Date: Thu, 16 Oct 2025 09:43:07 +0530 Subject: [PATCH] Implement Singleton Design Pattern in Java --- Singleton Design Pattern in Java.java | 35 +++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Singleton Design Pattern in Java.java diff --git a/Singleton Design Pattern in Java.java b/Singleton Design Pattern in Java.java new file mode 100644 index 000000000000..22a9974b5538 --- /dev/null +++ b/Singleton Design Pattern in Java.java @@ -0,0 +1,35 @@ +// Singleton Pattern Example +public class Singleton { + // Step 1: Create a private static instance of the same class + private static Singleton instance; + + // Step 2: Make the constructor private so no one can instantiate directly + private Singleton() { + System.out.println("Singleton instance created!"); + } + + // Step 3: Provide a public static method to get the instance + public static Singleton getInstance() { + if (instance == null) { + // Lazy initialization + instance = new Singleton(); + } + return instance; + } + + // Example method + public void showMessage() { + System.out.println("Hello from Singleton Pattern!"); + } + + // Test it + public static void main(String[] args) { + Singleton s1 = Singleton.getInstance(); + Singleton s2 = Singleton.getInstance(); + + s1.showMessage(); + + // Checking if both objects are same + System.out.println("Are both instances same? " + (s1 == s2)); + } +}