싱글턴패턴은 인스턴스가 오직 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를 가진다는 것이다.
참고로 스프링에서는 IoC Contatainer를 이용해 private constructor, static method 없이 Java class를 싱글턴으로 관리할 수 있도록 해준다.