public class Singleton {
//자기 자신의 객체 생성
private static final Singleton instance = new SingletonS();
//getInstance 메소드로만 조회 가능
public static Singleton getInstance(){
return instance;
}
//생성자를 private으로 설정한다
private Singleton(){
}
}
@Test
@DisplayName("싱글톤 패턴을 적용한 객체 사용")
void singletonTest() {
new Singleton();
}
}
<에러메시지>
java: Singleton() has private access in hello.hellospring.singleton.Singleton
위의 코드로 테스트를 하면 오류가 발생한다.
즉, 싱글톤패턴이 잘 적용된 것을 확인할 수 있다.
@Test
@DisplayName("싱글톤 패턴을 적용한 객체 사용")
void singletonService() {
Singleton singleton1 = SingletonService.getInstance();
Singleton singleton2 = SingletonService.getInstance();
System.out.println(singleton1);
System.out.println(singleton2);
}
<실행결과>
hello.hellospring.singleton.SingletonService@23a5fd2
hello.hellospring.singleton.SingletonService@23a5fd2
실행결과를 보면 동일한 객체 인스턴스가 반환된 것을 확인할 수 있다.
즉, 객체가 여러번 생성되는 것이 아니라 동일한 인스턴스를 사용하는 것을 볼 수 있다.
매번 싱글톤패턴을 적용해 코딩을 해야하는걸까?
답은 NO! 스프링 컨테이너를 사용하자.
모든 객체를 싱글톤으로 만들지 않더라도 스프링 컨테이너에 등록된 객체는 스프링 컨테이너가 객체를 싱글톤으로 만들어서 관리해준다