单例
public class Singleton { public static int STATUS = 1; private Singleton() { System.out.println("Singleton is created"); } private static Singleton instance = new Singleton(); public static Singleton getInstance() { return instance; } public static void main(String[] args) { //任何对Singleton方法或字段的应用,都会导致类初始化,并创建instance实例 System.out.println(Singleton.STATUS); //但是类初始化只有一次,因此instance试了永远只会被创建一次,所以调用Singleton.getInstance() //不会输出 Singleton is created Singleton.getInstance(); } }
延迟加载
public class LazySingleton { public static int STATUS = 1; private LazySingleton() { System.out.println("LazySingleton is create"); } private static LazySingleton instance = null; public static synchronized LazySingleton getInstance() { if(instance == null) { instance = new LazySingleton(); } return instance; } public static void main(String[] args) { System.out.println(LazySingleton.STATUS); //延迟加载,只会在instance被第一次使用时,创建对象 //因此,只有调用getInstance()方法时才会创建对象 LazySingleton.getInstance(); } }
加强版单例
综合上述 Singleton 和 LazySingleton 优点的单例
/** * 拥有Singleton 和 LazySingleton 的优点 * Singleton 优点: getInstance() 没有使用Synchronized 加锁 * LazySingleton 优点:直到instance 实例被使用时,才创建instance 对象 * */ public class StaticSingleton { public static int STATUS = 1; private StaticSingleton() { System.out.println("StaticSingleton is create"); } private static class SingletonHolder { private static StaticSingleton instance = new StaticSingleton(); } public static StaticSingleton getInstance() { return SingletonHolder.instance; } public static void main(String[] args) { System.out.println(StaticSingleton.STATUS); StaticSingleton.getInstance(); } }