用内部类来维护单例的实现
public class Singleton {
//私有构造方法,防止被实例化 private Singleton(){}
//用一个内部类来维护单例 private static class SingletonFactory{ private static Singleton singleton=new Singleton(); }
//获取实例 public static Singleton getInstance(){ return SingletonFactory.singleton; } }
使用锁实现单例
public class Singleton { private static Singleton singleton=null; private Singleton(){} private static synchronized void syncInit() { if (singleton == null) { singleton = new Singleton(); } } public static Singleton getInstance(){ if (singleton == null){ syncInit(); } return singleton; } }