Singleton Pattern
There can be only one.
Singleton Pattern
Analogy: pattern
The Singleton Pattern is like a King.
A Kingdom can only have ONE King. If you ask for the King, you get the same person every time. You don't get a new King cloned for every request.
The King
Try to create multiple Kings.
- The first time, a King is born (Created).
- Every subsequent time, the SAME King is returned.
The King (Singleton Pattern)
Laws of the Land
"There can be only ONE King in the Kingdom instance!"
The Royal Court
Empty Throne
Kingdom Access Log
// Waiting for constructor call...The Code
Make the constructor private and provide a static method to get the instance.
Java Example
Switch language in Navbar
class King {
private static King instance;
// Private Constructor
private King() {}
public static King getInstance() {
if (instance == null) {
instance = new King();
}
return instance;
}
}
Up Next
Factory Pattern