饿汉模式:
class Singleton { private Singleton() {} private static Singleton singleton = new Singleton(); public static Singleton getInstance() { return singleton; } }
懒汉模式:
public class Singleton { private Singleton() {} private static Singleton singleton = null; public static Singleton getInstance() { if (singleton == null) { synchronized (Singleton.class) { // 以当前类的字节码对象为锁 if (singleton == null) { singleton = new Singleton(); } } } return singleton; } }