How to create a singleton class

前端 未结 7 1082
粉色の甜心
粉色の甜心 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;
        }
    }
    

提交回复
热议问题