Singleton
Pour le c#
Version super simplifié
public class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton()
{
}
public static Singleton Instance
{
get
{
return Instance;
}
}
}
{
private static readonly Singleton instance = new Singleton();
private Singleton()
{
}
public static Singleton Instance
{
get
{
return Instance;
}
}
}
Version (mono-thread)
public class Singleton
{
private static Singleton instance;
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
{
private static Singleton instance;
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
Version (multi-threads)
public class Singleton
{
private static Singleton instance;
static readonly object instanceLock = new object();
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (instanceLock)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
{
private static Singleton instance;
static readonly object instanceLock = new object();
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (instanceLock)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
Version (multi-threads) - Autre implémentation possible, depuis le .Net 4, sans lock
f
public class Singleton
{
private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}
{
private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}