KH/JAVA

# 26 Singleton pattern

오늘의 진 2022. 7. 19. 14:29

 

Singleton pattern

 

소프트웨어 디자인 패턴에서 싱글턴 패턴( Singleton pattern )을 따르는 클래스는
생성자가 여러차례 호출되더라도 실제로 생성되는 객체는 하나이고 
최초 생성 이후에 호출된 생성자는 최초의 생성자가 생성한 객체를 리턴한다.
이와 같은 디자인 유형을 싱글턴 패턴이라고 한다
주로 공통된 객체를 여러개 생성해서 사용하는 DBCP(DataBase Connection Pool)와 같은 상황에서 많이 사용된다.

 

 

final class Singleton {

	private static Singleton ss;   // = new Singleton();

	private Singleton() {   }

	public static Singleton getInstance() { 
    // 생성자가 private이므로 class내부에서 객체생성
		if (ss == null) { 
        //ss는 처음 생성하고 초기화 하지 않았음으로 기본값은 null이다.
			ss = new Singleton();
		}
		return ss;
        // 객체가 null이 아니라면 즉 이미 만들어져있으면 return ss 있던 ss를 리턴하겠다/쓰겟다는말.
	}

}

class HelloWorld {
}

public class SingletonTest {
	public static void main(String[] args) {

		// Singleton ss = new Singleton();
		// 생성자가 private라서 class 외부에서 호출 불가능함 
        //clss내부에서 메소드를 통해서  인스턴스를 생성해야한다.

		Singleton ss1 = Singleton.getInstance(); // ss1, ss2 모두 미리 만들어두었던 ss반환
		Singleton ss2 = Singleton.getInstance();

		System.out.println("Singleton 객체 ss1 hashCode : " + ss1.hashCode());
		System.out.println("Singleton 객체 ss1 hashCode : " + ss1);

		System.out.println("Singleton 객체 ss2 hashCode : " + ss2.hashCode());
		System.out.println("Singleton 객체 ss2 hashCode : " + ss2);

		System.out.println("==========================================================");

		HelloWorld hh1 = new HelloWorld();
		HelloWorld hh2 = new HelloWorld();

		System.out.println("HelloWorld 객체 hh1  hashCode : " + hh1.hashCode());
		System.out.println("HelloWorld 객체 hh1  hashCode : " + hh1);
		System.out.println("HelloWorld 객체 hh2  hashCode : " + hh2.hashCode());
		System.out.println("HelloWorld 객체 hh2  hashCode : " + hh2);

	}

}
Singleton 객체 ss1 hashCode : 1865127310      // haschCode가 같다 == 같은 객체이다. 
Singleton 객체 ss1 hashCode : ja_0719.Singleton@6f2b958e
Singleton 객체 ss2 hashCode : 1865127310
Singleton 객체 ss2 hashCode : ja_0719.Singleton@6f2b958e ==========================================================
HelloWorld 객체 hh1 hashCode : 474675244  // 10진수인 이숫자를 16 진수로 바꾸면 아래의 1c4af82c가 됨
HelloWorld 객체 hh1 hashCode : ja_0719.HelloWorld@1c4af82c
HelloWorld 객체 hh2 hashCode : 932583850
HelloWorld 객체 hh2 hashCode : ja_0719.HelloWorld@379619aa

( 해석 )

final class Singleton {

	private static Singleton ss; //= new Singleton();
	private Singleton() {
	}
	public static Singleton getInstance() { 
		if (ss == null) { 
			ss = new Singleton();
		}
		return ss; 
	}
}

여기에서 private static Singleton ss 라고 해서 Singleton 타입의 ss를 만들어 두었지만 new Singleton(); 하지 않았음으로 비어있는 null 상태이다. 

이때 메인 메소드에서 Singleton ss1 = Singleton.getInstance(); 을 이용하여 getInstance()를 실행하면 ss== null 이므로 

if 내부가 실행되어 인스턴스가 하나 만들어져서 ss에 담기게 된다. 

ss2에서는 ss에 이미 인스턴스가 담겨있음으로 만들어 져있던 인스턴스가 반환된다. 

즉 ss1 , ss2 모두  같은 ss 인스턴스를 이용하게된다. 

그로인해 hashCode 값이 같은 값으로 반환된다. 

또한 ss는 인스턴스가 아니라 ss1 ss2 모두에서 접근함으로

static 으로 메소드 영역에 고정해둠( private static Singleton ss; )