单例模式

单例模式(饿汉式)

public void Demo(){

private stataic final Demo instance = new Demo();

//构造方法私有化
private Demo(){
}

public static Demo getInstance(){
  return instance;
}
}

单例模式(懒汉式)

public void Demo(){

private stataic Demo instance = null  ;

//构造方法私有化
private Demo(){
}

public static Demo getInstance(){
  if(instance != null){
    instance = new Demo();
   }
return instance;
}
}

解决两种的弊端的单例模式(双锁)

public void Demo(){
 private static Demo d;
 private static Object init_click = new Object();
 //构造方法私有化
 private Demo(){

}
//双锁:解决延迟加载问题
public static Demo getInstance(){
    if(null==d){
    synchronized(init_click){
        if(d==null){
            d = new Demo();
            }
        }
    }
    return d;
 }
 

}   

你可能感兴趣的:(单例模式)