====== Singleton ======
===== Singleton vs. static class =====
**Singleton**
* + we can use singletons as parameters
* + control over instantion
**Static class**
* - lazy initialization
* + easier
===== Implementations =====
==== With locks ====
* Standard solution using locks.
public sealed class Singleton
{
static Singleton _instance=null;
static readonly object _lock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (_lock)
{
if (_instance==null)
{
_instance = new Singleton();
}
return _instance;
}
}
}
}
==== Without locks ====
* Elegant solution without locks.
public sealed class Singleton
{
static readonly Singleton _instance=new Singleton();
static Singleton()
{
}
Singleton()
{
}
public static Singleton Instance
{
get
{
return _instance;
}
}
}
==== Without cycle ====
* Solves complications if one static constructor invokes another which invokes the first again. Solution breaks the cycle.
public sealed class Singleton
{
Singleton()
{
}
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
===== Refrences =====
* [[http://www.yoda.arachsys.com/csharp/singleton.html]]
* [[http://dotnet.dzone.com/news/c-singleton-pattern-vs-static-]]