본문 바로가기
개발 교육

spring 싱글톤 패턴

by azure05 2023. 12. 14.

오늘은 싱글톤 패턴에 대해 배워보도록 한다. 

 

 

 

첫번째 조건, 프로젝트에서 유일한 객체

 

두번째 조건, 실수로 1개 이상의 객체가 만들어 지지 않도록 클래스 작성

 

 

 

코드 내용

package Pack01;

 

 

class Apple{

 

private static Apple apple = null;

 

//생성자

private Apple() {

 

}

 

static Apple getInstance() {

if(apple==null) {

apple = new Apple();

}

return apple;

}

 

}

 

 

 

public class Hello {

public static void main(String[] args) {

System.out.println(1);

Apple a1 = Apple.getInstance();

Apple a2 = Apple.getInstance();

Apple a3 = Apple.getInstance();

 

System.out.println(a1.hashCode());

System.out.println(a2.hashCode());

System.out.println(a3.hashCode());

 

}

}

 

코드 결과 화면

1

1586600255

1586600255

1586600255



'개발 교육' 카테고리의 다른 글

리액트 2일차 12/20  (0) 2023.12.20
다형성  (0) 2023.12.14
Kafka (2)  (0) 2023.12.12
스프링 12/12  (0) 2023.12.12
kafka란 무엇인가 (1)  (0) 2023.12.11