1. 의도
클래스의 개체 생성을 하나의 인스턴스로만 제한합니다.
2. 용도
단 하나의 유일한 객체를 만들기 위해서 사용합니다.
즉, 해당 인스턴스가 필요할 때 새로운 인스턴스를 만들지 않고 기존의 인스턴스를 가져와 활용하는 방법입니다.
예를 들어 파일에 환경설정(동적으로 변경되지 않음)정보가 있을 때, Singleton 패턴을 적용하지 않으면
필요 시 매번 객체를 생성하고 로드하는 비용이 발생합니다.
반면에 Singleton 패턴을 적용하면 최초 한번만 해당 객체를 로드하고 이후에는 로드한 객체를 사용할 수 있습니다.
3. UML
4. 구현
- synchronized 이용
public class Settings {
// 1 - 인스턴스 뽑을 때마다 동기화 하기 때문에 성능이슈 생길 수 있음
private Settings() {}
private static Settings instance;
public static synchronized Settings getInstance() {
if (instance == null) {
instance = new Settings();
}
return instance;
}
}
- 이른 초기화 방법
public class Settings {
// 2 - 이른 초기화 (미리 만든다는 것이 단점이 될 수 있다.)
private Settings() {}
private static final Settings INSTANCE = new Settings();
public static Settings getInstance() {
return INSTANCE;
}
}
- double checked locking
public class Settings {
// 3 - double checked locking
private Settings() {}
private static volatile Settings instance;
public static Settings getInstance() {
if (instance == null) {
synchronized (Settings.class) {
if (instance == null) {
instance = new Settings();
}
}
}
return instance;
}
}
- static inner 클래스 사용
public class Settings {
// 4 - static inner 클래스 사용
private Settings() {}
private static class SettingsHolder {
private static final Settings INSTANCE = new Settings();
}
public static Settings getInstance() {
return SettingsHolder.INSTANCE;
}
}
- enum 사용
public enum Settings {
INSTANCE;
}
각 방법마다 장단점이 있어서 고려해서 사용해야 합니다.
5. Singleton 패턴의 장단점
- 장점
- 클래스가 하나의 인스턴트만 갖게 할 수 있습니다.
- 이 인스턴스에 대한 전역 접근 지점을 얻습니다.
- 단점
- 모듈간 의존성이 높아질 수 있습니다.
- 단일책임원칙(SRP)을 위반합니다.
- 테스트를 하기 어려울 수 있습니다.
출처 :
https://refactoring.guru/design-patterns/singleton
Singleton
Real-World Analogy The government is an excellent example of the Singleton pattern. A country can have only one official government. Regardless of the personal identities of the individuals who form governments, the title, “The Government of X”, is a g
refactoring.guru
'디자인 패턴' 카테고리의 다른 글
자바(JAVA) - 커맨드(Command) 패턴 (0) | 2023.11.01 |
---|---|
자바(JAVA) - 데코레이터(Decorator) 패턴 (0) | 2023.10.19 |
자바(JAVA) - 빌더(Builder) 패턴 (0) | 2023.10.18 |
자바(JAVA) - 전략(Strategy) 패턴 (0) | 2023.10.17 |
자바(JAVA) - 템플릿 메서드(Template Method) 패턴 (0) | 2023.10.13 |