这个单例模式,能实现再用时在进行对象的生成,同时又能避免繁琐且低性能的加锁机制。
这里巧妙的是利用了内部类,来实现单例的延迟初始化。在没有调用
getInstance方法时,jvm不会加载内部类,所以此时不会生成单例对象。当getInstance方法被调用时,但是单例才被生成。这个方法同时避免了,繁琐的双重加锁。
public class BestSingleton { public static BestSingleton getInstance(){ return iner.instance; } private BestSingleton(){} private static class iner{ public static final BestSingleton instance = new BestSingleton(); } }