싱글톤 패턴 공부

까만호랭·2023년 8월 14일
1

싱글톤 패턴?

Centered Image
  • 특정 클래스에 객체 인스턴스가 하나만 만들어지도록 하는 패턴이다. (하나의 객체를 공유하는 셈)
  • 싱글턴 패턴을 사용하면 전역변수를 사용할 때와 마찬가지로 객체 인스턴스를 어디서든지 액세스 할 수 있게 만들 수 있다.
  • 클래스 인스턴스를 하나만 만들고 그 인스턴스로의 전역 접근을 제공한다.
  • 사용 목적

    자동차 공장이라는 클래스를 생성하고 자동차 부품인 핸들, 바퀴 등 데이터들을 변수로 생성하고 관리할때 다른 클래스에서 자동차 공장 클래스에 접근할때 setter, getter로 접근하여 수정 또는 반환하여 사용한다.
    이러한 경우 다른 클래스에서 각자 인스턴스를 생성하게 된다면 다른 클래스들끼리 이 '자동차공장' 클래스의 정보를 공유하기가 어려운 문제점이 생기는데
    이떄 싱글톤 패턴이라는 것을 사용하면 정보를 보관하고 공유하고자 하는 클래스가 한 번의 메모리만 할당하고 그 할당한 메모리에 대해 객체로 관리한다.
    (각각의 자동차 공장이란 클래스에서 생성자를 호출하더라도 처음 한번 생성된 인스턴스를 반환해주기 때문에 변수 관리, 동기화에 좋다.)

    getInstance()

    외부에서 객체를 얻을때 사용하는 메소드

    싱글톤 패턴 사용

    public class Test15Singletom {
    	int kor=10;
    	private static Test15Singletom singletom = new Test15Singletom(); //static이면 밖에서 클래스의 이름으로 바로 부를 수 있음 -> Test15.~~
    	public static Test15Singletom getInstance() { // 밖에서 private이라 못부르기 때문에 pulbic static 매소드를 만듬 //getInstance는 Test15tom를 반환 -> staitc이 될수밖에 없어서 써줌
    		return singletom; //객체변수의 주소를 던짐
    	}
    }
    
    public class Test15SingletomMain {
    	public static void main(String[] args) {
        
    		Test15Singletom s1=new Test15Singletom();
    		Test15Singletom s2=new Test15Singletom();
    		// 두개의 객체는 주소가 다름 : pack2.Test15Singletom@63440df3 : pack2.Test15Singletom@3aeaafa6
    		System.out.println(s1+" "+s2);
    		System.out.println(s1.kor+" "+s2.kor);
    		
    		System.out.println();
    		Test15Singletom ss1=Test15Singletom.getInstance(); //new가 끝난 객체를 받음(주소 받음)--singleTom이 반환형
    		Test15Singletom ss2=Test15Singletom.getInstance();
    		//외부에서 호출 시 new를 사용하지 않고 getInstance를 사용하여 객체를 생성하거나 반환받습니다.
    
    		// 두 개의 객체 주소가 같음 : pack2.Test15Singletom@76a3e297 : pack2.Test15Singletom@76a3e297
    		System.out.println(ss1+" "+ss2);
    		System.out.println(ss1.kor+" "+ss2.kor);
            // 인스턴스를 따로 써야할 상황이면 10~14행 사용, 아니면 17~21행 사용
    	}
    }

    Test15Singletom s1=new Test15Singletom();
    Test15Singletom s2=new Test15Singletom();
    의 코드는 s1, s2를 각각 Test15Singletom 클래스에서 새로운 객체를 생성한 것이기에 서로 다른 객체 주소를 가지는 것을 알 수 있다.
    반면에
    Test15Singletom ss1 = Test15Singletom.getInstance();
    Test15Singletom ss2 = Test15Singletom.getInstance();
    의 코드의 ss1, ss2는 Test15Singletom 클래스의 getInstance() 메소드 내에서는 클래스 레벨의 private static Test15Singletom singletom 변수를 사용하여 싱글톤 인스턴스를 유지합니다.

    정리

    싱글톤 패턴을 사용하여 객체를 생성할 때는 getInstance() 메소드를 사용하여 항상 동일한 객체를 가져와야 한다. 이렇게 하면 객체의 주소가 항상 같게 된다.

    profile
    남들과 함께 발자국을 남기는 까만호랭

    0개의 댓글