디자인 패턴

싱글톤 패턴(3) - 자바와 스프링에서 찾아보는 패턴

깊게 생각하고 최선을 다하자 2022. 8. 31. 04:04

- 자바의 기본 Runtime 인스턴스는 싱글톤 패턴을 활용한 코딩을 통해 얻어낼 수 있습니다. 

  Runtime 인스턴스는 런타임 환경에 대한 정보를 제공합니다. 

public class RuntimeExample{

    public static void main(String[] args){
        Runtime runtime = Runtime.getRuntime();
        System.out.println(runtime.maxMemory());
        System.out.println(runtime.freeMemory());
    }
}

 

- 또한, 스프링에서 제공하는 스프링 컨테이너에는 싱글톤 스코프로 빈을 등록해서 사용합니다.  

@Configuration
public class SpringConfig{

   @Bean
   public String hello(){
       return "hello";
   } 
 }
public class SpringExample{

    public static void main(String[] args){
       ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
       String hello = applicationContext.getBean("hello", String.class);
       String hello2 = applicationContext.getBean("hello", String.class);
       System.out.println(hello == hello2);
    }
}

// 실행 결과
true

- 또한 다른 디자인 패턴(빌더, 퍼사드, 추상 팩토리 등)의 구현체의 일부로 쓰이기도 합니다. 

 

참고

백기선  코딩으로 학습하는 GoF의 디자인 패턴