✔ 주로 공통된 객체를 여러개 생성해서 사용하는 DBCP(DataBase Connection Pool)와 같은 상황에서 많이 사용된다.
✔ 싱글톤 패턴은 객체의 인스턴스를 한 개만 생성되게 하는 패턴 이다.
✔ 이러한 패턴은 주로 프로그램 내에서 하나로 공유를 해야하는 객체가 존재할 때 해당 객체를 싱글톤으로 구현해서 모든 사용자 또는 프로그램이 해당 객체를 공유하며 사용하도록 할 때 사용한다.
✔ 싱글톤 패턴을 사용하는 경우
📌 프로그램 내에서 하나의 객체만 존재해야 하는 경우
📌 프로그램 내에서 여러 부분에서 해당 객체를 공유하여 사용해야한다.
: 한 개의 인스턴스만을 고정 메모리 영역에 생성하고 추후 해당 객체를 접근할 때 메모리 낭비를 방지할 수 있다.
: 생성된 인스턴스를 사용할 때는 이미 생성된 인스턴스를 활용하여 속도 측면에 이점이 있다.
: 전역으로 사용하는 인스턴스이기 때문에 다른 여러 클래스에서 데이터를 공유하며 사용할 수 있다.
하지만 동시성 문제가 발생할 수 있어 유의하여 설계해야 한다.
public class Singleton {
// 단 1개만 존재해야 하는 객체의 인스턴스로 static 으로 선언
private static Singleton instance;
// private 생성자로 외부에서 객체 생성을 막아야 한다.
private Singleton() {
}
// 외부에서는 getInstance() 로 instance 를 반환
public static Singleton getInstance() {
// instance 가 null 일 때만 생성
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
< public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
public class Singleton {
private static Singleton instance;
private static int count = 0;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
public static void plusCount() {
count++;
}
}
private static Singleton instance = new Singleton();
public class Singleton {
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronzied Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
}