티스토리 뷰

JAVA/Design Pattern

Singleton Pattern

쟌쥰 2019. 11. 17. 16:11
package com.singleton;

/*
 * singleton
 * 
 * memory(heap)에 객체를 한번만 생성한다.
 * 
 * new 연산자를 사용할 수 없다. static으로 생성된 객체 하나를 호출한다!! 
 * 이미 생성되어 있던 객체의 주소값을 참조한다. 단 한번만 생성된다!
 */
public class Singleton {

	// 2. 객체의 주소값을 확인할 변수를 static으로 선언!
	private static Singleton singleton;

	// 1. 생성자를 외부에서 호출할 수 없도록 private으로 선언!!!!!!!!!!!!!!!
	private Singleton() {
		System.out.println("singleton instance 생성!!!!!!!!!!!!!!");
	}

	// 3. 객체가 heap에 존재하는지 확인한다.
	// 만일 없으면 생성하고, 있으면 만들어져 있는 객체의 주소값을 리턴
	public static Singleton getInstance() {

		if (singleton == null) {
			singleton = new Singleton();
			System.out.println("new!");
		} else {
			System.out.println("exists!");
		}

		return singleton;
	}
}
package com.singleton;

public class MTest {

	public static void main(String[] args) {
		//Singleton singleton = new Singleton();
		Singleton singleton = Singleton.getInstance();
		System.out.println(singleton.hashCode());
		
		Singleton st01 = Singleton.getInstance();
		System.out.println(st01.hashCode());
		
		Singleton st02 = Singleton.getInstance();
		System.out.println(st02.hashCode());
	}
}
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함