Last active
August 1, 2017 06:22
-
-
Save djkeh/3cbbce75df1617541ecfee2638255784 to your computer and use it in GitHub Desktop.
static 사용을 제한한 싱글턴 구조의 표현
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
} |
Gist에 알림 기능이 없어 댓글을 이제야 확인했습니다. 늦은 답신 죄송합니다. 싱글턴 패턴을 적용할 때 그 정도를 관대하거나 엄격하게 조절할 수 있다는 사실이 신선하게 다가오네요. 친절한 답변 정말 감사합니다!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
public
은 공개 범위를 뜻합니다.final
인가,abstract
인가는 직교 차원이죠. 따라서 Java의 경우non-public
이라 하면 패키지 범위가 되겠죠.static
을 사용하는 것과 서비스를 소비하는 측에서static
을 사용하는 것은 많이 다릅니다.