public class Singleton { private static Singleton instance; private Singleton (){} public static synchronized Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
方法二:饿汉
在单例类被加载时候完成实例化
1 2 3 4 5 6 7
public class Singleton { private static final Singleton instance = new Singleton(); private Singleton (){} public static Singleton getInstance() { return instance; } }
public class Singleton { private volatile static Singleton singleton; private Singleton (){} public static Singleton getSingleton() { if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } }
方法四:枚举
1 2 3 4 5
public enum Singleton { INSTANCE; public void mothed() { } }
方法五:静态内部类
1 2 3 4 5 6 7 8 9
public class Singleton { private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } private Singleton (){} public static final Singleton getInstance() { return SingletonHolder.INSTANCE; } }