- @참고: https://javaplant.tistory.com/21

 

- 싱글톤 패턴이란

Singleton 패턴은 인스턴스를 불필요하게 생성하지 않고 오직 JVM내에서 한 개의 인스턴스만 생성하여 재사용을 위해 사용되는 디자인패턴이다.

 

6. LazyHolder Singleton 패턴 - 5에서 사용안하는 인스턴스를 만들어 놓는 문제를 개선

더보기
public class Singleton {
    private Singleton(){}
    
    public static Singleton getInstance() {
    	return LazyHolder.INSTANCE;
    }
    
    private static class LazyHolder {
    	private static final Singleton INSTANCE = new Singleton();
    }
}

 

5. static 초기화를 이용한 Singleton 패턴 - 간결한 소스와 성능 개선

더보기
public class Singleton {
	private static Singleton instance;
    
    static {
    	instance = new Singleton();
    }
    
    private Singleton(){}
    
    public static Singleton getInstance() {
    	return instance;
    }
}

 

4. volatile 을 이용한 개선된 DCL Singleton 패턴 (jdk 1.5 이상에서 사용) - 3에서 인스턴스를 null 로 줄 수 있는 문제점 개선

더보기
public class Singleton {
	private volatile static Singleton instance;
    
    private Singleton(){}
    
    public static Singleton getInstance() {
    	if (instance == null) {
        	synchronized (Singleton.class) {
            	if (instance == null) {
                	instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

 

(사용해선 안됨)3. DCL(Double-Checked-Locking) Singleton 패턴 - 2에서 생기는 lock 의 효율성을 개선

더보기
public class Singleton {
	private static Singleton instance;
    
    private Singleton(){}
    
    public static Singleton getInstance() {
    	if (instance == null) {
        	synchronized (Singleton.class) {
            	if (instance == null) {
                	instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

 

2. synchronized 를 이용한 Singleton 패턴 - multi-thread 환경에서 1에서 두개의 인스턴스가 생길 가능성을 개선

더보기
public class Singleton {
	private static Singleton instance;
    
    private Singleton(){}
    
    public static synchronized Singleton getInstance() {
    	if (instance == null) {
        	instance = new Singleton();
        }
        return instance;
    }
}

 

1. 고전적 방식의 Singleton 패턴

더보기
public class Singleton {
	private static Singleton instance;
    
    private Singleton(){}
    
    public static Singleton getInstance() {
    	if (instance == null) {
        	instance = new Singleton();
        }
        return instance;
    }
}

'Design Pattern' 카테고리의 다른 글

디자인 패턴의 분류  (0) 2020.01.03
블로그 이미지

uchacha

개발자 일지

,