1. 程式人生 > >單例設計模式的實現程式碼

單例設計模式的實現程式碼

 

package test;

public class Singleton {

 /**
  *
  * @author Administrator/2012-3-1/上午09:07:06
  */
 public static void main(String[] args) {

  Singleton s1=Singleton.getInstance();
  Singleton s2=Singleton.getInstance();
  Singleton s3=Singleton.getInstance();
  System.out.println("s1="+s1);
  System.out.println("s2="+s2);
  System.out.println("s3="+s3);
  

 }

  /*** SingletonHolder is loaded on the first execution of Singleton.getInstance() 
   * * or the first access to SingletonHolder.INSTANCE, not before.  
   * */
 private static class SingletonHolder {
  public static final Singleton INSTANCE = new Singleton();
 }

 //Private constructor prevents instantiation from other classes
 private Singleton() {
 }

 public static Singleton getInstance() {
  return SingletonHolder.INSTANCE;
 }

}