728x90
반응형
What is Singleton?
=> A singleton is a class that allows only a single instance of itself to be created and gives access to that created instance.
LazyHolder Singleton Pattern
public class Singleton {
// LazyHolder Singleton pattern
private Singleton(){};
private static class LazyHolder{
public static final Singleton instance = new Singleton();
}
public static Singleton getInstance(){
return LazyHolder.instance;
}
}
getInstance()를 호출했을때 LazyHolder 클래스가 로딩되면서 생성
장점 : 객체가 필요한 시점에서 초기화가 진행된다.
동일 인스턴스가 생성되는지 테스트
public class Main {
public static void main(String[] args) {
// singleton test
// LazyHolder Singleton pattern test
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance();
System.out.println(singleton1);
System.out.println(singleton2);
System.out.println(singleton1 == singleton2);
}
}
결과값
com.example.demo.domain.Singleton@39ed3c8d
com.example.demo.domain.Singleton@39ed3c8d
true
728x90
반응형