C \ # 단일 모드 의 실현
3631 단어 C \ # - 디자인 모드
, 。 :
public class Singleton {
private static Singleton singleton;
private Singleton() {}
public static Singleton GetInstance()
{
if (singleton == null)
{
singleton = new Singleton();
}
return singleton;
}
, GetInstance() , 。 :
public class Singleton {
private static Singleton singleton;
static readonly object Padlock = new object();
private Singleton() {}
public static Singleton GetInstance()
{
if (singleton == null)
{
lock(Padlock)
{
if (singleton == null)
{
singleton = new Singleton();
}
}
}
return singleton;
}
GetInstance() , , , 。 ( , ( 、 、 ) )。
public class Singleton {
private static Singleton singleton = new Singleton();
private Singleton() {}
public static Singleton GetInstance()
{
return singleton;
}
}
。 , 。
public class Singleton {
private Singleton() {}
static class SingletonHolder
{
private static final Singleton singleton = new Singleton();
}
public static Singleton getInstance()
{
return SingletonHolder.singleton;
}
}
/ , , 。 , , , 。