-
Item 3: Enforce the singleton property with a private constructor or an enum type독서/Effective Java 2021. 12. 4. 19:48
private 생성자나 열거 타입으로 싱글턴임을 보증하자
싱글톤?
정확히 한 번 인스턴스화되는 클래스 일반적으로 함수(Item 24)와 같은 상태 비저장 개체, 본질적으로 고유한 시스템 구성 요소를 의미함.
단점
클래스를 싱글톤으로 만들면 해당 유형의 역할을 하는 인터페이스를 구현하지 않는 한 싱글톤에 대한 Mocking을 대체하는 것이 불가능하고, 이 때문에 클라이언트를 테스트하기 어렵다.
싱글톤을 구현하는 두 가지 일반적인 방법
1. public static final 필드 변수 제공
public class Elvis { public static final Elvis INSTANCE = new Elvis(); private Elvis() { ... } public void leaveTheBuilding() { ... } }
INSTANCE가 호출되는 시점에 새로운 Elvis가 만들어지고, 그 이후로는 유지된다.
권한 있는 클라이언트가 AccessibleObject.setAccessible 메서드를 사용하여 private 생성자를 반사적으로 호출할 수 있지만(Item 65), private 생성자에 두 번째 객체가 생성되려 할 때 예외를 던지게 하면 된다.
2. Static Factory Method - getInstance 제공
public class Elvis { private static final Elvis INSTANCE = new Elvis(); private Elvis() { ... } public static Elvis getInstance() { return INSTANCE; } public void leaveTheBuilding() }
3. Enum 방식으로 생성
// Enum singleton - the preferred approach public enum Elvis { INSTANCE; public void leaveTheBuilding() { ... } }
- public 필드 방식과 비슷하지만, 더 간결하다.
- 추가 노력없이 직렬화가 가능하다.
- 아주 복잡한 직렬화 상황이나 리플렉션 공격에서도 제 2의 인스턴스가 생기는 상황을 완벽히 막아준다.
정리
대부분의 상황에서는 원소가 하나뿐인 열거 타입이 싱글턴을 만드는 가장 좋은 방법이다.
단, 만들려는 싱글턴이 Enum 외의 클래스를 상속해야 한다면 이 방법은 사용할 수 없다.'독서 > Effective Java' 카테고리의 다른 글
Item 6: Avoid creating unnecessary objects (0) 2021.12.04 Item 5: Prefer dependency injection to hardwiring resources (0) 2021.12.04 Item 4: Enforce noninstantiability with a private constructor (0) 2021.12.04 Item 2: Consider a builder when faced with many constructor parameters (0) 2021.12.04 Item 1. Consider static factory methods instead of constructors (0) 2021.12.04