Skip to content

Commit acc5966

Browse files
authored
Implement Singleton Design Pattern in Java
1 parent ede37bd commit acc5966

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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+
}

0 commit comments

Comments
 (0)