안녕하세요^^ 싱글톤패턴에 대해 여쭤보고 싶습니다.

kikiki0611의 이미지

안녕하세요~

자바에서 싱글톤 패턴을 공부하던 도중 의문점이 생겨서요~
아래 A)와 B)의 차이점을 정확히 잘 모르겠어서요,

A의 경우도 static이라 어차피 클래스 생성 시간에 1번만 생성되는게 아닌가요?

A)

public class Single {
	private static Single instance = new Single();
	private Single() {};
 
	public static Single getInstance(){
		return instance;
	}
}

B)

public class Single {
	private static Single instance; 
	private Single() {};
 
	public static Single getInstance(){
		if( instance == null )
			instance = new Single();
		return instance;
	}
}

goforit의 이미지

자바는 제가 본지 아주 오래되서 구글을 찾아 보았습니다.

일단 B) 이 부분은
private static Single instance;

A) 달리 바로 instance에 Object 가 생성되서 할당되는 것은 아니구요. (1) 따라서 B에서 getInstance을 호출시 null일 수 있다고
보여집니다.

그리고 B)의 getInstance() 함수 구현은 이 약속된 Single Pattern의 개념을 그대로 구현한 것 같습니다.
아래 영어 문장을 한번 보세요.(2)

Classically, the Singleton pattern can be implemented by creating a class with a method that creates a new instance of the class if one doesn't exist. In the event of an instance already existing, it simply returns a reference to that object.

참조)
(1) Declaring a Variable to Refer to an Object) https://docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html
(2) JavaScript: The Singleton Pattern : https://addyosmani.com/resources/essentialjsdesignpatterns/book/#singletonpatternjavascript

kikiki0611의 이미지

친절한 답변 감사합니다^^
제가 드리고자 했던 말씀은, A와 B모두 기능적으로 똑같이 동작을 하는 것 같은데 어째서 A는 틀리고 B의 방식대로 구현이 되는걸까요?
라는 질문이었습니다