Java单例模式
懒汉式单例
1.适用于单线程环境(不推荐)
1 | public static Singleton getInstance(){ |
2.适用于多线程环境,但效率不高(不推荐)
1 | public static synchronized Snigleton getInstance(){ |
3.双重检验锁(推荐)
1 | public static Singleton getInstance(){ |
4.静态内部类(Effective Java 上推荐)
1 | private static class SingletonHolder{ |
饿汉式单例
static final
1 | private static final Singleton INSTANCE=new Singleton(); |
枚举单例
enum
1 | public enum EasySingleton{ |