오직 하나의 인스턴스만 생성할 수 있는 클래스 입니다.
public class Student {
public static final Student STUDENT = new Student();
private Student() {
}
}
private으로 선언되어 있어서, 외부에서 접근할 수 없습니다.STUDENT 객체를 생성할 때 딱 한번 호출됩니다.단, 이 방식에는 취약점이 있다.
public class Student {
public static final Student STUDENT = new Student();
private Student() {
}
public static void main(String[] args) {
try {
Constructor<Student> constructor = Student.class.getDeclaredConstructor();
constructor.setAccessible(true);
Student instance = constructor.newInstance(); // private 생성자를 호출하여 객체를 생성합니다.
System.out.println(instance);
} catch (Exception e) {
e.printStackTrace();
}
}
}
리플렉션 API 인 AccessibleObject.setAccessible() 메서드로 private 생성자를 호출 할 수 있다.
private static int instanceCount = 0;
private Student() {
if (instanceCount > 0) {
throw new IllegalStateException("생성자는 한번만 호출될 수 있습니다.");
}
instanceCount++;
}
이 경우에는, 생성자에서 두번째 객체가 생성되려 할 때 예외를 던지면 됩니다.
public class SecondSingleton {
private static final SecondSingleton INSTANCE = new SecondSingleton();
private SecondSingleton() {
}
public static SecondSingleton getInstance() {
return INSTANCE;
}
}
getInstance(정적 팩터리 메서드)로 가져옵니다.가짜 객체의 탄생을 예방하려면
readResolve 메서드(아이템 89에서 더 자세히 다루겠습니다.)를 제공해야 합니다.public enum EnumSingleton {
INSTANCE
}
item 24, 30, 43, 44, 89