싱글턴은 같은 종류의 객체가 하나만 존재하도록 하고, 해당 객체에 대한 단일 접근 지점을 제공하는 생성 디자인 패턴이다.
public sealed class Singleton
{
private Singleton() { }
private static Singleton _instance;
public static Singleton GetInstance()
{
if (_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
public void someBusinessLogic()
{
// ...
}
}
class Program
{
static void Main(string[] args)
{
Singleton s1 = Singleton.GetInstance();
Singleton s2 = Singleton.GetInstance();
if (s1 == s2)
{
Console.WriteLine("Singleton works, both variables contain the same instance.");
}
else
{
Console.WriteLine("Singleton failed, variables contain different instances.");
}
}
}
출력
Singleton works, both variables contain the same instance.
class Singleton
{
private Singleton() { }
private static Singleton _instance;
private static readonly object _lock = new object();
public static Singleton GetInstance(string value)
{
if (_instance == null)
{
lock (_lock)
{
if (_instance == null)
{
_instance = new Singleton();
_instance.Value = value;
}
}
}
return _instance;
}
public string Value { get; set; }
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(
"{0}\n{1}\n\n{2}\n",
"If you see the same value, then singleton was reused (yay!)",
"If you see different values, then 2 singletons were created (booo!!)",
"RESULT:"
);
Thread process1 = new Thread(() =>
{
TestSingleton("FOO");
});
Thread process2 = new Thread(() =>
{
TestSingleton("BAR");
});
process1.Start();
process2.Start();
// Join():
// 현재 스레드 객체의 작업이 완료되거나 종료될 때까지 기본 스레드의 실행을 대기
process1.Join();
process2.Join();
}
public static void TestSingleton(string value)
{
Singleton singleton = Singleton.GetInstance(value);
Console.WriteLine(singleton.Value);
}
}
출력
FOO
FOO