java单例模式

public class Singleton {  
  private static Singleton s=new Singleton(); 
  private Singleton(){};
  /**
   * Class method to access the singleton instance of the class.
   */
  public static Singleton getInstance() {
    return s;
  }
}

 

 

public class Singleton {

	private volatile static Singleton singleton;
	
	private Singleton(){ }
	
	public static Singleton getInstance(){
		// 双重检查加锁
		if(singleton==null){
			synchronized(Singleton.class){
				// 延迟实例化,需要时才创建
				if(singleton==null)
					singleton = new Singleton();
			}
		}
		return singleton;
	}
}

 

 

http://www.iteye.com/topic/897652

你可能感兴趣的:(java)