2013년 1월 29일 화요일

싱글턴 패턴(Singleton Pattern)

출처: Head First Design Patterns : 스토리가 있는 패턴 학습법

싱글턴 패턴(Singleton Pattern)
싱글턴 패턴은 해당 클래스의 인스턴스가 하나만 만들어지고, 어디서든지 그 인스턴스에 접근할 수 있도록 하기 위한 패턴이다.

디자인 패턴을 모르더라도 대부분 알고 있고 유용하게  사용하고 있는 패턴이다. 책에서는 보통 사용하고 있는 싱글턴 패턴 코드에 대해서 고전적인 싱글턴 패턴이라고 말을 하면서, 멀티쓰레드에서는 제대로 작동하지 않는다고 하는데... 멀티쓰레드 되면 프로그램 구조에 대해서 다시 생각해 봐야 하므로 당연한 말이 아닌지....

아무튼 이건 Class Diagram 보다는 코드를 보는게 더 이해가 빠르다.(Class Diagram 에 박스 하나 밖에 없으므로....)

[Java]
1. Thread-unsafe
public class Singleton {
    private static Singleton uniqueInstance;

    private Singleton() {}

    public static Singleton getInstance() {
        if(uniqueInstance == null) {
            uniqueInstance = new Singleton();
        }
        return uniqueInstance;
    }
}

2. Thread-safe
public class Singleton {
    private volatile static Singleton uniqueInstance;
    
    private Singleton() {}

    public static Singletone getInstance() {
        if(uniqueInstance == null) {
            synchronized(Singleton.class) {
                if(uniqueInstance == null) {
                    uniqueInstance = new Singleton();
                }
            }
        }
    }
}


[Objective C]
1. Thread-safe
@impelement Singoleton
static Singleton* sharedInstance = nil;
+ (id)sharedInstance {
    if(sharedInstance != nil) return sharedInstance;
    
    static dispatch_once_t pred;
    dispatch_once(&pred, ^{
        sharedInstance = [[self alloc] init];
    });
    
    return sharedInstance;
}
@end

멀티쓰레드가 된다면 만들어 놓고 디버깅 하려면 무지 힘드니, Singleton 을 사용한다면 프로그램 구조 설계 할때 잘 생각해서 구현 하도록 하자. 생성 외에 내부 메소드들도 멀티쓰레드 동작이 반영 되어야 할 것이다.

댓글 없음:

댓글 쓰기