Singleton Pattern
[tr] Türkçe Oku 2023-06-11
Once upon a time, there was a ruler in the Singular Realm. The ruler’s name was “Singleton”, and he had the property of being the only entity in the whole realm. Singleton had educated everyone else about preserving his uniqueness and singularity.
Being the sole ruler of his kingdom, Singleton was recognized with the property of being a unique entity that, once created, could not be changed again. In every corner of the kingdom, it was known that Singleton was created only once and only one instance existed. This unique feature allowed Singleton to rule in his kingdom.
This story is implemented in the C# language as follows:
public class Singleton
{
private static Singleton _instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
}
}
The same story in Java language:
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
In Python:
class Singleton:
_instance = None
@staticmethod
def getInstance():
if Singleton._instance == None:
Singleton()
return Singleton._instance
def __init__(self):
if Singleton._instance != None:
raise Exception("This class is a singleton!")
else:
Singleton._instance = self
This story in Go language:
package singleton
import "sync"
var instance *Singleton
var once sync.Once
type Singleton struct{}
func GetInstance() *Singleton {
once.Do(func() {
instance = &Singleton{}
})
return instance
}
This story in Rust language:
use std::sync::Mutex;
pub struct Singleton {
//...
}
lazy_static! {
static ref SINGLETON: Mutex<Singleton> = Mutex::new(Singleton {
//...
});
}
pub fn get_instance() -> &'static Mutex<Singleton> {
&SINGLETON
}
And thus, the story of the Singleton design pattern is told. Singleton is a way of creating a single instance of a class and providing this single instance to the whole system. This is commonly used to manage global states or control shared resources. The Singleton pattern is used to prevent recurring creation operations, use resources efficiently, and provide consistency across the system.