싱글톤 패턴

ITKHJ·2023년 1월 13일
0

GoF의 디자인 패턴

목록 보기
1/16
post-thumbnail

/**

  • private 생성자와 public static 메소드를 사용하는 방법
    */
    public class Settings1 {

    private static Settings1 instance;
    
    //밖에서 new을 사용하지 못하게 하기 위해
    //private 생성자 생성
    private Settings1() { }
    
    //글로벌 접근이 가능하게 하기 위해
    // static 생성
    public static Settings1 getInstance() {
        //생성자가 없을때만 생성자 생성
        if (instance == null) {
            instance = new Settings1();
        }
    
        return instance;
    }

}
문제점

멀티 쓰레드를 사용할 시 동시에 조건에 진입하게 되면 두개의 인스턴스가 만들어 지는 문제점 발생

문제해결 방법 - 1

synchronized 를 사용하여 한개의 쓰레드만 들어오게 하는 방법

getInstance를 이용할때 마다 synchronized 처리를 하기 때문에 성능 저하가 일어날 수 있다.

/**

  • private 생성자와 public static 메소드를 사용하는 방법
    */
    public class Settings1 {

    private static Settings1 instance;
    
    //밖에서 new을 사용하지 못하게 하기 위해
    //private 생성자 생성
    private Settings1() { }
    
    //글로벌 접근이 가능하게 하기 위해
    // static 생성
    //synchronized를 이용해서 한개의 쓰레드만 들어오게 하는 방법
    public static synchronized Settings1 getInstance() {
        //생성자가 없을때만 생성자 생성
        if (instance == null) {
            instance = new Settings1();
        }
    
        return instance;
    }

}
문제해결 방법 - 2

이른 초기화(eager initialization) 사용하기

/**

  • private 생성자와 public static 메소드를 사용하는 방법
    */
    public class Settings {
    //미리 생성자를 생성
    private static final Settings INSTANCE = new Settings();
    //밖에서 new을 사용하지 못하게 하기 위해
    //private 생성자 생성
    private Settings() { }
    
    public static Settings GetInstance() {
        return INSTANCE;
    }

}
문제해결 방법 - 3(권장)

double checked locking 사용하기

자바 1.5부터 사용가능

/**

  • private 생성자와 public static 메소드를 사용하는 방법
    */
    public class Settings1 {

    private static volatile Settings1 instance;
    
    //밖에서 new을 사용하지 못하게 하기 위해
    //private 생성자 생성
    private Settings1() { }
public static Settings1 getInstance() {
    //생성자가 없을때만 생성자 생성
    if (instance == null) {
        synchronized(Settings1.class){
          if(instance == null){
              instance  = new Setting();
          }
        }
    }

    return instance;
}

}
문제해결 방법 - 4(권장)

static inner 클래스 사용하기

자바 1.4이하에서도 사용가능한 방법

/**

  • private 생성자와 public static 메소드를 사용하는 방법
    */
    public class Settings1 {
    private Settings1() {}

    private static class SettingHolder(
    private static final Settings1 INSTANCE = new Settings1 ();
    )

public static Settings1 getInstance() {
    return SettingHolder.INSTANCE;
}

}

profile
모든 업무 지식 작성하자!

0개의 댓글