[Hackerrank] Advanced - Singleton Pattern 풀이

예문


https://www.hackerrank.com/challenges/java-singleton/problem

Sample Input

hello world

Sample Ouput

Hello I am a singleton! Let me say hello world to you

해석

  • Singleton Pattern 구현

풀이

  • LazyHolder 방식
    • Assert 에러가 남;;
    • DCL(Double Checked Locking) 방식으로 제출함.

제약사항

코드

//LazyHolder 방식
public class Singleton {
    private Singleton() {}
    public String str;

    public static Singleton getSingleInstance() { return LazyHolder.INSTANCE; }

    private static class LazyHolder {
        private static final Singleton INSTANCE = new Singleton();
    }
}

//DCL 방식
class Singleton {
    private volatile static Singleton instance;
    public static String str;
    private Singleton() {}

    static Singleton getSingleInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}