싱글톤은 실행 중인 Java 프로그램에서 객체가 1개만 생성되어 사용되도록 보장하는 패턴입니다.

public class Singleton {
	
    // 싱글톤 객체 생성 저장 공간
	private static Singleton singleton = null;
	static int cnt =0;
    
    // 외부 접근 금지
	priavte Singleton() {
    	// 생성자가 한번만 생성됨
		cnt++;
		System.out.println(cnt+"번 생성되었습니다.");
	}
	
    // 싱글톤을 통해서 객체 반환 
	public static Singleton getInstance() {
    	// 싱글톤 객체가 없을 경우 새로 생성.
		if(singleton == null) {
			singleton = new Singleton();
		}
		return singleton;
	}
	
}

 

결과 출력시 다음과 같이 여러번 호출하여도 1번만 생성된다.

 

참고해두면 좋을 싱글톤 여러가지 선언방법

 

https://sorjfkrh5078.tistory.com/108

+ Recent posts