Singleton Design Patterns
You live in a country, and there’s only one President leading the nation.
No matter how many citizens there are, they all have to follow the same President.
You can't just go and appoint a new President every time someone wants one. That would be
chaotic, confusing, and dangerous for the country.
So, the system ensures:
● Only one President is ever elected.
● Everyone recognizes and interacts with that same President.
That President is your Singleton class.
The Singleton design pattern ensures:
● Only one instance (object) of a class is ever created.
● Everyone who needs that class uses the same instance.
Example:
// Singleton Class
public class President {
private static President instance;
// Private constructor to prevent instantiation
private President() {
[Link]("A President has been elected.");
}
// Public method to provide access to the instance
public static President getInstance() {
if (instance == null) {
instance = new President(); // Lazy initialization
}
return instance;
}
// Sample method to demonstrate functionality
public void announce() {
[Link]("I am the President of this country.");
}
}
public class Main {
public static void main(String[] args) {
President p1 = [Link]();
[Link]();
President p2 = [Link]();
[Link]();
// Check if both are the same object
if (p1 == p2) {
[Link]("Both p1 and p2 refer to the same President
instance.");
} else {
[Link]("Different President instances exist (which
shouldn't happen in Singleton).");
}
}
}
Output:
A President has been elected.
I am the President of this country.
I am the President of this country.
Both p1 and p2 refer to the same President instance.