- 정의
- 클래스의 인스턴스는 하나만 생성 가능
- 그 인스턴스로의 전역접근을 제공
- 전역변수의 단점 보완
- 생성자를private로 선언
public class Singleton {
//하나뿐인 인스턴스를 저장하는 정적 변수
private static Singleton uniqueInstance;
//private 로 선언했으므로 singleton 에서만 인스턴스 생성 가능
private Singleton() {}
//인스턴스 == null >> 인스턴스가 아직 생성되지 않음
public static Singleton getInstance() {
//싱글턴 객체 생성 후 uniqueInstance 에 객체 대입
//게으른 인스턴스 생성 이라고 부름
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
public String getDescription() {
return "클래식 싱글턴";
}
}
- 클래식 싱글턴
public class Singleton {
private static Singleton uniqueInstance;
private Singleton() {}
//getInstance 메소드를 동기화
//한 스레드가 사용을 끝내기 전까지 다른 스레드는 접근 불가
public static synchronized Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
public String getDescription() {
return "thread-safe Singleton";
}
}
- 동기화로 멀티스레딩 문제 해결
public class Singleton {
//정적 초기화 부분에서 인스턴스 생성
//스레드를 사용해도 문제가 발생하지 않음
private static Singleton uniqueInstance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return uniqueInstance;
}
public String getDescription() {
return "정적으로 초기화";
}
}
- 처음부터 생성하는 방법
public class Singleton {
//DCL(Double-Check-Locking)사용
//volatile 을 사용하면 멀티스레딩을 사용해도 초기화 과정이 올바르게 진행
private volatile static Singleton uniqueInstance;
private Singleton() {}
public static Singleton getInstance() {
//인스턴스가 null 이면 동기화 된 블록으로 이동
if (uniqueInstance == null) {
//처음에만 동기화
synchronized (Singleton.class) {
//변수가 null 인지 다시 한 번 확인 후 인스턴스 생성
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
public String getDescription() {
return "DCL";
}
}
- DCL을 사용하는 방법
public enum Singleton {
UNIQUE_INSTANCE;
public String getDescription() {
return "enum";
}
}
- Enum을 사용
GitHub - Pearlmoon997/Design_Patterns: Design_Patterns
Design_Patterns. Contribute to Pearlmoon997/Design_Patterns development by creating an account on GitHub.
github.com
참고문서: 헤드퍼스트 디자인패턴(개정판)
'디자인패턴' 카테고리의 다른 글
Builder Pattern (0) | 2022.05.23 |
---|---|
Singleton Pattern_ver.02 (0) | 2022.05.22 |
Factory Method_ver.02 (햄버거) (0) | 2022.05.19 |
Abstract Factory _ 피자가게 (0) | 2022.05.18 |
FactoryMethod _ 피자가게 (0) | 2022.05.18 |