반응형
싱글톤 패턴은 최초 한번만 메모리를 할당하고 객체를 만들어 사용하는 디자인 패턴으로 생성자를 반복호출해도 최초 생성된 객체를 반환해준다.
장점
- 객체를 한개만 만들어서 메모리 낭비가 적다
- 싱글톤 객체와 다른 객체들 간의 데이터 공유가 쉽다
단점
- 싱글톤 클래스의 역할이 커지면 결합도가 높아져 객체 지향 원칙에 어긋날 수 있다.
- 멀티쓰레드 환경에서 중복 초기화가 발생할 수 있다.
싱글톤을 구현하는 여러 방법
static 활용
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return instance;
}
}
위 방법은 애플리케이션 실행시 정적으로 객체 생성
이 방법의 경우 실행시 바로 객체를 생성하는 방법으로 객체의 크기가 커지면 부담이 될 수 있다.
class 로드전 정적 생성으로 Thred-Safe하다.
지연 생성 방법
public class Singleton {
private static Singleton instance;
private Singleton(){}
public static Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
위 방법은 멀티 스레드 환경에서 예기치 못한 문제를 만들 수 있다. (두 스레드가 getInstance를 동시에 한 경우)
synchronized 사용 방법
public class Singleton {
private static Singleton instance;
private Singleton(){}
public static synchronized Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
synchronized를 사용하면 멀티 스레드 환경에서 Thred-safe할 수 있다.
다만 synchronized에 의한 성능저하가 발생할 수 있다.
Inner Class 활용
public class Singleton {
private Singleton(){}
private static class SingletonHelper{
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance(){
return SingletonHelper.INSTANCE;
}
}
해당 방법은 내부 클래스를 활용한 방법이다.
getInstance를 호출하기 전까지 Singleton 객체가 생성되지 않으며, getInstance호출 시 정적 객체 생성
객체가 바로 생성되지 않는 지연 생성 방법이며 정적 인스턴스로 syncronized를 사용하지 안하 성능 저하도 없다.
반응형