싱글톤 패턴의 다양한 예제

기본 패턴

public class ExampleCls {
	private static ExampleCls instance;

	private ExampleCls() {}
	
	public static ExampleCls getInstance() {
		if (instance == null) {
			instance = new ExampleCls();
		}
	
		return instance;
	}
}

Synchronized 사용(Thread-Safe)

public class ExampleCls {
	private static ExampleCls instance;

	private ExampleCls() {}
	
	public static synchronized ExampleCls getInstance() {
		if (instance == null) {
			instance = new ExampleCls();
		}
	
		return instance;
	}
}
  • 동시성 문제는 해결되지만, 성능에 저하가 발생할 수 있음

(Lazy) Double check 싱글톤

public class ExampleCls {
	private volatile static ExampleCls instance;

	private ExampleCls() {}
	
	public static ExampleCls getInstance() {
		if (instance == null) {
			synchronized(ExampleCls.class) {
				if (instance == null) {
					instance = new ExampleCls();
				}
			}
		}
	
		return instance;
	}
}
  • instance가 null인 것을 확인한 후에 synchronized를 적용하여 성능 개선
  • Lazy 기법에 해당함

LazyHolder(현재 Java 싱글톤 패턴에서 가장 일반적으로 사용)

public class ExampleCls {
	private ExampleCls() {}
	
	public static class ExampleCls LazyHolder() {
		private static final ExampleCls instance = new ExampleCls();
	}

	public static ExampleCls getInstance() {
		return LazyHolder.instance;
	}
}
  • JVM의 특성을 활용한 Thread-Safe 싱글톤 패턴
  • Class를 로드 및 초기화하는 시점에 Thread-Safe를 보장하는 것을 이용한 패턴

싱글톤 패턴의 문제점

  • 객체 지향 설계에 대한 안티 패턴이 될 수 있음
    • 싱글톤에서는 생성자가 private이기 때문에 상속이 어려움

+ Recent posts