Singleton:
ensures a class has only one instance, and provides a global point of access to it.
Java example 1:
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
Java example 2:
public class Singleton {
private static Singleton instance = new Singleton();;
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
C# example1:
public class Singleton
{
private volatile static Singleton _instance = null;
private static readonly object lockHelper = new object();
private Singleton(){}
public static Singleton CreateInstance()
{
if(_instance == null)
{
lock(lockHelper)
{
if(_instance == null)
_instance = new Singleton();
}
}
return _instance;
}
}
C# example 2:
public class Singleton
{
private Singleton(){}
public static readonly Singleton instance = new Singleton();
}