의미
싱글톤(Singleton) 패턴은 소프트웨어 디자인 패턴 중 하나로, 특정 클래스에 대해 인스턴스를 하나만 생성하고, 그 인스턴스에 전역적으로 접근할 수 있도록 보장하는 패턴입니다. 이 패턴은 애플리케이션 전체에서 공통된 자원을 관리하거나 설정을 공유할 때 유용하게 사용됩니다. 예들으로 어떤 프로젝트에서 다음과 같은 경우에 사용하는 것을 생각해 볼 수 있습니다.
- 로그 관리: 애플리케이션 전역에서 로그를 기록할 때, 하나의 로그 관리 객체를 사용하여 일관된 로그 형식을 유지할 수 있습니다.
- 설정 관리: 애플리케이션의 설정 값을 저장하고 관리할 때, 하나의 설정 관리 객체를 통해 전역적으로 접근할 수 있도록 할 수 있습니다.
- 데이터베이스 연결: 데이터베이스와의 연결을 관리하는 객체가 하나만 존재해야 할 때, 싱글톤 패턴을 사용하여 중복 연결을 방지할 수 있습니다.
Java 에서 적용해보기
1. Eager Initialization (즉시 초기화): 클래스가 로드될 때 인스턴스가 생성됩니다. 간단하지만 클래스가 사용되지 않아도 인스턴스가 생성된다는 단점이 있습니다.
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {
// private constructor
}
public static Singleton getInstance() {
return instance;
}
}
2. Lazy Initialization (지연 초기화): 인스턴스가 필요할 때 생성됩니다. 하지만 멀티스레드 환경에서 동기화 문제가 발생할 수 있습니다.
public class Singleton {
private static Singleton instance;
private Singleton() {
// private constructor
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
3. Thread-safe Singleton (스레드 안전한 싱글톤) : Double-checked locking 기법을 사용하여 스레드 안전성을 보장하면서도 성능을 최적화합니다.
public class Singleton {
private static volatile Singleton instance;
private Singleton() {
// private constructor
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
Kotlin 에서 적용해보기
1. Object 선언 : 코틀린에서는 object키워드를 사용하여 간단하게 싱글톤을 구현할 수 있습니다. 이는 기본적으로 스레드 안전성을 보장합니다.
object Singleton {
// Singleton properties and methods
}
2. Lazy Initialization (지연 초기화) : 인스턴스가 필요할 때 초기화되며, 기본적으로 스레드 안전성을 보장하지 않기 때문에 멀티스레드 환경에서 주의가 필요합니다.
class Singleton private constructor() {
companion object {
private var instance: Singleton? = null
fun getInstance(): Singleton {
if (instance == null) {
instance = Singleton()
}
return instance!!
}
}
}
3. Thread-safe Singleton with by lazy: by lazy를 사용하여 스레드 안전하게 싱글톤 인스턴스를 초기화할 수 있습니다.
class Singleton private constructor() {
companion object {
val instance: Singleton by lazy {
Singleton()
}
}
}
'CS 질문' 카테고리의 다른 글
면접 전 체크할 CS 기본질문 10가지 (0) | 2024.08.17 |
---|---|
자바 스프링(Java Spring)과 고랭(Go) 비교하시오. (0) | 2024.08.15 |
객체 지향 프로그래밍 (OOP)이란 무엇인가? (0) | 2024.08.14 |
배열과 링크드 리스트의 차이점은 무엇인가요? (자바 기준) (0) | 2024.08.14 |
HTTPS 에 대해서 설명하시오. (0) | 2024.08.14 |