싱글톤패턴

클래스 내부에서 객체를 하나만 생성하여 공유해서 사용하는 기법

메모리 절약 목적으로 웹에서 사용

public class Singleton {
	
    //외부에서 직접 접근할 수 없고 메모리에 미리 올려둠
	//객체 생성은 하지 않고 선언만
	private static Singleton instance= null;
	
	//클래스 내부에서만 객체 생성가능
	private Singleton() {
		System.out.println("인스턴스 생성");
	}
	//외부에서 미리 만들어둔 객체에 접근할 수 있도록 정적메소드로 작성
	public static Singleton getInstance() {
		//객체가 만들어져 있지 않으면 생성
		if(instance==null) {
			synchronized(Singleton.class) {//(공유할 객체명)
				//한 스레드가 작업하는 동안은 다른 스레드에서 접근할 수 없게함
				instance=new Singleton();
			}
		}
		return instance;
	}
}
package j210125;

public class MainTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Singleton ob1 = Singleton.getInstance();
		Singleton ob2 = Singleton.getInstance();		
		Singleton ob3 = Singleton.getInstance();
		//객체명은 3개이지만 실제 주소값은 같은 동일한 객체이다
		System.out.println(ob1);
		System.out.println(ob2);
		System.out.println(ob3);
	}
}
/*
인스턴스 생성
j210125.Singleton@15db9742
j210125.Singleton@15db9742
j210125.Singleton@15db9742
*/

 

+ Recent posts