다양한 싱글톤 생성 방법

서현서현·2023년 8월 6일
0

JAVA

목록 보기
26/27

싱글톤

싱글톤 예제는 하나만 알고있었는데, 다른 생성예제들이 많았다...ㅎㅎ 이참에 공부!!
(CF) 싱글톤은 객체의 인스턴스가 오직 하나만 생성되는 패턴이다

Eager Initialization

static을 통해 class가 로드될때 객체를 생성한다.
객체를 사용하지 않더라도 생성되므로 자원낭비가 될 수 있다는 단점

class Singleton {
	private static Singleton instance = new Singleton();
    
    private Singleton() {}
    
    public static Singleton getInstance(){
    	return instance;
    }
}

static Block Initialization

static 블록을 이용하여 Exception처리를 해주는 방법
static 블록은 초기화 블록으로도 불리며, 클래스가 처음 로딩될때 한번만 수행되는 블록이다. 하지만 이방법도 자원의 비효율성을 해결하진 못함

class Singleton{
	private static Singleton singleton;
    
    private Singleton(){};
    
    static{
    	try{
        	singleton = new Singleton();
        }catch(Exception e) {
        	throws new RuntimeException("singleton error");
        }
    }
    
    public static Singleton getInstance(){
    	return singleton;
    }
}

Lazy Initialization

원래 쓰던 방법이다. 자원의 비효율성을 해결할 수 있으나 다른문제가 있다.

public class Singleton {
	private static Singleton instance;
    private Singleton(){}
    public static Singleton getInstance(){
    	if(instance == null) instance = new Singleton();
        return instance;
    }
}

싱글톤 패턴은 한 객체를 여러곳에서 접근하므로 멀티 스레드 환경에서 동기화 문제를 발생시킨다. 만약 한번에 여러곳에서 getInstance() 메소드를 호출한다면 여러개의 객체가 생성될 수 있다. 즉 이 방법은 싱글스레드에선 괜찮지만 멀티스레드 환경에선 동기화 문제가 생긴다.

참고

0개의 댓글