Here is the most popular version of the implementation of this design pattern :
public class Singleton
{
private static Singleton instance;
private object oSync = new object();
public Singleton ()
{
}
public static Singleton Instance
{
get
{
if(instance == null)
{
Lock(oSync)
{
if(instance == null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
}
this version is not optimized for .Net. In .Net we can use a static constructor and this static constructor is ThreadSafe.
Here is the optimized version :
public class Singleton
{
private static Singleton instance = new Singleton ();
private object oSync = new object();
static Singleton ()
{
}
private Singleton ()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
mercredi 17 octobre 2007
Inscription à :
Commentaires (Atom)