
싱글톤 패턴(Singleton Pattern)은 특정 클래스의 인스턴스를 하나만 생성하도록 제한하는 디자인 패턴입니다.
이 패턴을 사용하면 전역적으로 접근 가능한 단일 객체를 보장할 수 있습니다.
싱글톤 패턴을 구현하는 여러 가지 방식이 있으며, 각각의 방식에 따라 장단점이 존재합니다.
public class Singleton {
private static Singleton instance;
private Singleton() {} // 생성자 private
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
public class Singleton {
private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
public class Singleton {
private Singleton() {}
private static class Holder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return Holder.INSTANCE;
}
}
public enum Singleton {
INSTANCE;
public void doSomething() {
System.out.println("싱글톤 인스턴스 메서드 호출");
}
}
| 장점 | 단점 |
|---|---|
| 전역적으로 동일한 인스턴스를 사용 가능 | 의존성이 증가하여 테스트하기 어려울 수 있음 |
| 객체 생성 비용 절감 | 멀티스레드 환경에서 구현 방식에 따라 동기화 비용 발생 |
| 메모리 절약 | 단일 인스턴스 사용으로 인해 가비지 컬렉션의 대상이 되지 않음 |
싱글톤 패턴은 애플리케이션에서 하나의 인스턴스만 유지해야 하는 경우에 적합합니다.