싱글톤을 구현하는 가장 간단한 방법
1. 생성자를 private으로 감추기 2. public static 멤버를 통해 딱하나만 생성한 인스턴스 제공하기
멤버 - 생성자, 메서드, 필드
메서드 Ver - 정적 팩터리 메서드를 public static 멤버로 제공
사용 안해도 생성, 예외처리 불가
사용 안하면 안생성, 예외처리 가능
1. 생성자를 private으로 감추기 2. public static 멤버를 통해 딱하나만 생성한 인스턴스 제공하기
// Thread Unsafe, Eager Initilization class Singleton { private static final Singleton INSTANCE = new Singleton(); private Singleton() { } public static Singleton getInstance(){ return INSTANCE; } ... }
// Thread Unsafe, Lazy Initilization class Singleton { private static Singleton instance; private Singleton() { } public static Singleton getInstance(){ if (instance == null) instance = new Singleton(); return instance; } }
public class Singleton{ public static final Singleton INSTANCE = new Singleton(); private Singleton() {} }