Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions Singleton Design Pattern in Java.java
Original file line number Diff line number Diff line change
@@ -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));
}
}
Loading