File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change 1+ // Singleton Pattern Example
2+ public class Singleton {
3+ // Step 1: Create a private static instance of the same class
4+ private static Singleton instance ;
5+
6+ // Step 2: Make the constructor private so no one can instantiate directly
7+ private Singleton () {
8+ System .out .println ("Singleton instance created!" );
9+ }
10+
11+ // Step 3: Provide a public static method to get the instance
12+ public static Singleton getInstance () {
13+ if (instance == null ) {
14+ // Lazy initialization
15+ instance = new Singleton ();
16+ }
17+ return instance ;
18+ }
19+
20+ // Example method
21+ public void showMessage () {
22+ System .out .println ("Hello from Singleton Pattern!" );
23+ }
24+
25+ // Test it
26+ public static void main (String [] args ) {
27+ Singleton s1 = Singleton .getInstance ();
28+ Singleton s2 = Singleton .getInstance ();
29+
30+ s1 .showMessage ();
31+
32+ // Checking if both objects are same
33+ System .out .println ("Are both instances same? " + (s1 == s2 ));
34+ }
35+ }
You can’t perform that action at this time.
0 commit comments