싱글톤 (Singleton) 패턴
- 싱글톤 패턴
- 인스턴스를 오직 하나만을 생성하여 글로벌하게 환경설정이나 시스템 런타임등에 사용한다.
- 간단한 싱글톤 코드
- 생성자를 private로 설정을 해주면 사용할때 new로 만들기가 불가능하다.
- static 으로 getInstance를 만든 이유는 글로벌하게 접근을 하기 위해서 사용을 한다.
public class Settings {
private static Settings instance;
private Settings() { }
public static Settings getInstance() {
if (instance == null) {
instance = new Settings();
}
return instance;
}
}
위에 코드는 멀티 쓰레드 환경에서는 new Settings가 될수 있다.
멀티쓰레드의 접근을 막고 싶다면 synchronized 를 사용한다.
public static synchronized Settings getInstance() {
if (instance == null) {
instance = new Settings();
}
return instance;
}
'디자인 패턴' 카테고리의 다른 글
[디자인패턴] 팩토리(Factory)패턴 (0) | 2022.04.08 |
---|---|
[디자인패턴] 빌더(Builder)패턴 (0) | 2022.04.08 |
커맨드 패턴 (0) | 2021.12.21 |