본문 바로가기

자바

Singleton 이해하는 예제

package pack.my;


public class SingletonTestMain {

public static void main(String[] args) {

Car car1 = new Car();

Car car2 = new Car();

System.out.println(car1 + " : " + car2);

SingletonTest test1 = new SingletonTest();

SingletonTest test2 = new SingletonTest();

System.out.println(test1 + " : " + test2);

test1.aa();

System.out.println();

SingletonTest s1 = SingletonTest.getinstance();

SingletonTest s2 = SingletonTest.getinstance();

System.out.println(s1 + " : " + s2);

s1.aa();

}

}


====================================================================================


package pack.my;


public class SingletonTest {

private static SingletonTest test = new SingletonTest();

public SingletonTest(){

System.out.println("싱글톤 패턴에 의한 객체는 1회만 생성됨");

}

public static SingletonTest getinstance(){

return test;

}

public void aa(){

System.out.println("aa 출력");

}

}