How to create a singleton class

前端 未结 7 1011
粉色の甜心
粉色の甜心 2020-12-02 13:10

What is the best/correct way to create a singleton class in java?

One of the implementation I found is using a private constructor and a getInstance() method.

<
相关标签:
7条回答
  • 2020-12-02 14:16

    I will implement singleton in below way.

    From Singleton_pattern described by wikiepdia by using Initialization-on-demand holder idiom

    This solution is thread-safe without requiring special language constructs (i.e. volatile or synchronized

    public final class  LazySingleton {
        private LazySingleton() {}
        public static LazySingleton getInstance() {
            return LazyHolder.INSTANCE;
        }
        private static class LazyHolder {
            private static final LazySingleton INSTANCE = new LazySingleton();
        }
        private Object readResolve()  {
            return LazyHolder.INSTANCE;
        }
    }
    
    0 讨论(0)
提交回复
热议问题