디자인패턴: 싱글톤

yshjft·2022년 1월 7일
0

Java, OOP

목록 보기
10/27

싱글톤(singleton)

✔︎ 딱 1개만 있어야한다.
✔︎ 인스턴스를 오직 1개만 만들어야 한다.
✔︎ thread-safe가 반드시 보장되어야 한다.

Eager Initialization(이른 초기화 방식)

public class Singleton {
	//private static으로 선언
	private static Singleton instance = new Singleton();
	
	//생성자
	private Singleton(){}
	
	//인스턴스 리턴
	public static Singleton getInstance() {
		return instance;
	}
}
  • 클래스내에 private static을 사용하여 instance 변수를 생성하면서 인스턴스화에 상관 없이 접근 가능하면서 instance 변수에 함부로 접근하지 못하도록한다.

  • 클래스가 로딩 될 때 싱글톤 객체가 생성된다.

Lazy Initialization

public class Singleton {
	private static Singleton instance;

	private Singleton(){}
	
	public static Singleton getInstance(){
		if(instance == null){
			instance = new Singleton();
		}
		return instance;
	}
}
  • 인스턴스가 사용되는 시점에서 싱글톤 인스턴스를 생성한다.
  • Multi-thread 환경에서 동기화가 필요하다.

    😱 싱글톤 파괴 😱
    A thread & B thread 접근 → instance == null → A thread에서 인스턴스 생성 & B thread에서 인스턴스 생성

Lazy Initialization with syncronized

public class Singleton {
	private static Singleton instance;

	private Singleton(){}
	
	public static synchronized Singleton getInstance(){
		if(instance == null){
			instance = new Singleton();
		}
		return instance;
	}
}
  • Synchronized 키워드를 통한 thread 동시 접근 해결 BUT synchronized로 인한 성능 저하
public class Singleton{
	private static Singleton instance;

	private Singleton(){}
	
	public static Singleton getInstance(){
		//Double-checked locking
		if(instance == null){
			synchronized (Singleton.class) {
				if(instance == null)
					instance = new Singleton();
			}
		}
		return instance;
	}
}
  • 인스턴스가 생성될때만 동기화를 하게 하여 성능 저하를 줄인다.

SOLID 관점

  • DIP 위반 : 구체적인 클래스에 의존
  • OCP 위반 : 다른 객체를 사용하게된다면 코드가 변경되어야 한다.

참고

profile
꾸준히 나아가자 🐢

0개의 댓글