推荐单例模式
/** * 单例模式 - 饿汉式 */ class Singleton { private Singleton() { } private static final Singleton instance = new Singleton(); public static Singleton getInstance() { return instance; } } /** * 单例模式 - 双检锁 */ class Singleton1 { private Singleton1() { } private static volatile Singleton1 instance = null; public static Singleton1 getInstance() { if (null == instance) { synchronized (Singleton1.class) { if (null == instance) { instance = new Singleton1(); } } } return instance; } } /** * 单例模式 - 静态内部类 */ class Singleton2 { private Singleton2() { } public static Singleton2 getInstance() { return SingletonInstance.instance; } private static class SingletonInstance { private static final Singleton2 instance = new Singleton2(); } } /** * 单例模式 - 枚举 */ enum Singleton3 { Instance; public void say(String s) { System.out.println(s); } }