싱글턴 디자인 패턴은 흔히 사용되는 패턴이지만 thread-safety 에 대한 논쟁이 있다.
그래서 동기화 블록으로 둘러쌓기도 한다.
+ (id) sharedInstance {
static EOCClass *sharedInstance = nil;
@synchronized(self) {
if (!sharedInstance) {
sharedInstance = [[self alloc] init];
}
}
return sharedInstance;
}
하지만 dispatch_once 라는 함수를 쓰면 훨씬 쉽게 구현할 수 있다.
// 토큰을 이용해서 블록이 (thread-safe 이면서 한 번만) 실행된다는 걸 보장한다.
// 물론 그러려면 항상 같은 토큰을 사용해야 한다. 즉 static 이나 global 로 선언해야 한다.
// synchronized 보다 훨씬 빠르다.
void dispatch_once(dispatch_once_t *token,
dispatch_block_t block);
+ (id) sharedInstance {
static EOCClass *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}