Skip to content

Instantly share code, notes, and snippets.

@djkeh
Last active August 1, 2017 06:22
Show Gist options
  • Save djkeh/3cbbce75df1617541ecfee2638255784 to your computer and use it in GitHub Desktop.
Save djkeh/3cbbce75df1617541ecfee2638255784 to your computer and use it in GitHub Desktop.
static 사용을 제한한 싱글턴 구조의 표현
// static 사용을 제한한 싱글턴 구조의 표현 예제
using System;
public class SingletonService
{
public string GetMessage() => "Hello World";
}
public class ClientModule
{
private readonly SingletonService _service;
public ClientModule(SingletonService service)
{
_service = service ?? throw new ArgumentNullException(nameof(service));
}
public void PrintMessage() => Console.WriteLine(_service.GetMessage());
}
public class IocContainer
{
private readonly Func<ClientModule> _factory;
public IocContainer(Func<ClientModule> factory)
{
_factory = factory ?? throw new ArgumentNullException(nameof(factory));
}
public ClientModule GetModule() => _factory.Invoke();
}
public class Program
{
public static void Main(string[] args)
{
var singleton = new SingletonService();
var container = new IocContainer(() => new ClientModule(singleton));
Run(container);
}
private static void Run(IocContainer container)
{
for (int i = 0; i < 5; i++)
{
ClientModule module = container.GetModule();
Execute(module);
}
}
private static void Execute(ClientModule module) => module.PrintMessage();
}
@djkeh
Copy link
Author

djkeh commented Aug 1, 2017

Gist에 알림 기능이 없어 댓글을 이제야 확인했습니다. 늦은 답신 죄송합니다. 싱글턴 패턴을 적용할 때 그 정도를 관대하거나 엄격하게 조절할 수 있다는 사실이 신선하게 다가오네요. 친절한 답변 정말 감사합니다!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment