单例模式

2016-10-14  本文已影响0人  842677250535

定义: 确保一个类只有一个实例,并提供一个全局访问点。

同步getInstance方法

public class Singleton{

  private static synchronized Singleton uniqueInstance;

private Singleton();

public static Singleton getInstance(){

       if(uniqueInstance == null){

         uniqueInstance = new Singleton();

   } 

return uniqueInstance;

  }

}

使用eagerly  create

public class Singleton{

private static Singleton uniqueInstance = new Singleton();

private Singleton();

public static Singleton getInstance(){

  return uniqueInstance;

}

}  

使用double check

public class Singleton{

private static volatile  Singleton uniqueInstance;

private Singleton();

public static Singleton getInstance(){

if(uniqueInstance == null){

synchronized(Singleton.class){

if(uniqueInstance == null){

uniqueInstance = new Singleton();

}

}

}

return uniqueInstance;

}

}

volatile: 

上一篇下一篇

猜你喜欢

热点阅读