1. 싱글톤 패턴(Singleton pattern)
- 싱글톤 패턴은 디자인 패턴의 한 종류로, 단 하나의 유일한 객체를 만들기 위한 코드 패턴이다.
- 자주 사용되는 객체나, 메모리를 많이 차지하는 객체 등을 싱글톤으로 만들면, 자원을 효율적으로 사용할 수 있습니다.
- 보통 싱글톤 패턴이 적용된 객체가 필요한 경우는 그 객체가 리소스를 많이 차지하는 역할을 하는 무거운 클래스일때 적합하다.
● 일반적으로 클래스는 필요에 따라 여러 개의 인스턴스를 생성할 수 있습니다. 이러한 인스턴스들은 각각 독립된 상태와 행동을 가질 수 있습니다.
● 싱글톤 패턴을 사용하면, 해당 클래스의 인스턴스는 오직 하나만 생성됩니다. 이 하나의 인스턴스는 전역적으로 접근 가능하며, 여러 모듈들이 이를 공유하게 됩니다. 이렇게 하면 여러 모듈들이 동일한 객체를 참조하게 되므로 상태 관리가 중앙집중적으로 이루어질 수 있습니다.
2. 싱글톤 패턴의 동작 원리
public class Singleton {
private static Singleton uniqueInstance;
private Singleton() { //외부에서 직접 인스턴스를 생성할 수 없도록 함
}
public static Singleton getInstance() { // Singleton 클래스의 인스턴스를 반환하는 역할
if (uniqueInstance == null) { // 인스턴스가 없으면 생성
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
싱글톤으로 이용할 클래스를 외부에서 new 생성자를 통해 인스턴스화 하는 것을 제한하기 위해 클래스 생성자 메서드에private 키워드를 붙여주면 된다.그리고 위 그림에서 볼 수 있듯이getInstance() 라는 메서드에 생성자 초기화를 해주어, 만일 클라이언트가 싱글톤 클래스를 생성해서 사용하려면 getInstance() 라는 메서드 실행을 통해instance 필드 변수가 null 일경우 초기화를 진행하고 null이 아닐경우 이미 생성된 객체를 반환하는 식으로 구성하면 된다
3. 싱글톤 패턴의 장점
- 메모리 절약: 객체 하나만 생성하기 때문에 메모리를 절약할 수 있습니다.
- 속도 향상: 객체 생성 과정을 한 번만 수행하기 때문에 속도를 향상시킬 수 있습니다.
- 코드 간결화: 코드 중복을 줄이고 코드를 간결하게 만들 수 있습니다.
- 쓰레드 안전성: 싱글톤 패턴은 자연스럽게 쓰레드 안전성을 제공합니다.
4. 싱글톤 패턴의 단점
- 유연성 부족: 싱글톤 클래스는 변경하기 어렵습니다.
- 테스트 어려움: 싱글톤 클래스는 테스트하기 어렵습니다.
- 역할 분리 위반: 싱글톤 클래스는 여러 역할을 수행하게 되어 역할 분리 원칙을 위반할 수 있습니다.
'Spring > Spring' 카테고리의 다른 글
[Spring] Bean이란? (0) | 2024.03.05 |
---|---|
[Spring] IoC, DIP, DI란? (0) | 2024.03.05 |
[Spring] 의존성 주입(Dependency Injection, DI) 이해하기 (0) | 2024.02.06 |
[Spring] 한글 인코딩 에러 해결(한글 ➡️ ??) (0) | 2024.02.03 |
[Spring] 스프링과 스프링부트 (0) | 2024.01.09 |