방치하기

홍대 자바 수업 : 객체의 수를 제한하는 방법론적. 본문

홍익대 Java/수업

홍대 자바 수업 : 객체의 수를 제한하는 방법론적.

Yi Junho 2009. 7. 24. 16:35
반응형

// Singleton.java

public final class Singleton {

   // Singleton object to be returned by getSingletonInstance
   private static Singleton singleton = new Singleton();//객체 하나 만 생성 

   // private constructor prevents instantiation by other objects
   private Singleton() //행성자는 막아 놓는다 
   {
      System.err.println( "Singleton object created." );
   }

   // return existing Singleton object
   public static Singleton getSingletonInstance() //객체를 리턴 .
   {
      return singleton;
   }
}



// SingletonTest.java


public class SingletonTest {
   
   // run SingletonExample
   public static void main( String args[] )
   {
      Singleton firstSingleton;
      Singleton secondSingleton;

      // create Singleton objects
      firstSingleton = Singleton.getSingletonInstance();
      secondSingleton = Singleton.getSingletonInstance();

	  System.out.println("firstSingleton : "  + firstSingleton);
	  System.out.println("secondSingleton : " + secondSingleton);
      // the "two" Singletons should refer to same Singleton
      if ( firstSingleton == secondSingleton )
         System.err.println( "firstSingleton and secondSingleton " +
            "refer to the same Singleton object" );
   }
}


반응형
Comments