- 인스턴스를 오직 한 개만 제공하는 클래스를 만든다.
- 시스템 런타임, 환경 세팅에 대한 정보 등, 인스턴스가 여러개 일 때 문제가 생길 수 있다.
- 이때, 인스턴스를 오직 한개만 만들어 제공하는 클래스가 필요하다.
싱글톤 패턴 구현
- 본인의 타입을 가지는 클래스 변수(static)을 생성한다.
- 생성자를 private로 만들어 접근을 막는다.
- 본인의 객체를 생성하여 반환하는 getInstance 함수를 만들고 내부에는 클래스 변수 null 체크 로직을 만든다.
1) 요청시 객체를 만들어 반환하는 방법
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance(0 {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
2) 미리 객체를 만들어 반환하는 방법
public class Singleton {
private static final Settings INSTANCE = new Settings();
private Settings() {}
public static Settings getInstance() {
return INSTANCE;
}
}
멀티 쓰레드 환경에서 안전하게 싱글톤 패턴을 구현
1) 요청시 객체를 만들어 반환하는 방법
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
2) 미리 객체를 만들어 반환하는 방법
public class Singleton {
private static Singleton INSTANCE = new Singleton();
private Singleton() {}
public static synchronized Singleton getInstance() {
return INSTANCE;
}
}
3) double checked locking으로 효율적으로 동기화 블록 만들기
public class Singleton {
private static voliate Singleton instance;
private Singleton() {}
public static synchronized Singleton getIntance() {
if(instance == null) {
synchronized(Singleton.class) {
if(instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}