싱글턴 패턴

종명·2021년 1월 23일
0

싱글턴 이란?

싱글턴패턴은 인스턴스가 오직 1개만 생성 되어야 하는 경우에 사용되는 패턴이다. 예를 들면 DBCP(Database Connection Pool) 같은 공통된 객체를 여러개 생성해서 사용해야 하는 경우 사용된다.

싱글턴 패턴 구현

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

다음과 같이 private 생성자로 더이상 객체를 만들수 없도록 하고 getInstance() 메서드를 통해 객체를 받아서 쓰도록 구현 할 수 있다.
이 코드는 멀티스레딩 환경에서 getInstance() 메서드에 동시에 접근하여 인스턴스가 두개 생성 될 수 있는 위험이 있다. 그래서 이른 초기화동기화 블럭 등으로 이러한 문제점을 해결하고 Thread-safe하게 만들 수 있다.

이른 초기화

public class Singleton {
    private static Singleton singleton = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {
        return singleton;
    }
}

동기화 블럭

public class Singleton {
    private static Singleton singleton;

    private Singleton() {}

    public static synchronized Singleton getInstance() {
        if(singleton == null) {
            singleton = new Singleton();
        }
        return singleton;
    }
}

이 외에도 몇가지 방법들이 더 있지만 공통적인 특징은 private constructor, static method를 가진다는 것이다.

싱글턴 패턴의 문제점

  • private 생성자 때문에 상속을 할수 없다.
  • 생성자를 통해 객체에 동적으로 정보를 주입할 수 없기 때문에 테스트하기 힘들다.
  • 싱글턴은 결과적으로 전역변수이다. 그래서 멀티 스레드 환경에서 생성뿐 아니라 안전하게 사용하기 위해 고려해야할 점들이 많다.

참고로 스프링에서는 IoC Contatainer를 이용해 private constructor, static method 없이 Java class를 싱글턴으로 관리할 수 있도록 해준다.

0개의 댓글