Java Singleton Design Pattern : Questions

后端 未结 11 681
渐次进展
渐次进展 2021-01-30 11:39

I had an interview recently and he asked me about Singleton Design Patterns about how are they implemented and I told him that using static variables and static methods we can i

11条回答
  •  青春惊慌失措
    2021-01-30 12:27

    Query 1:

    Different ways of creating Singleton

    1. Normal Singleton : static initialization
    2. ENUM
    3. Lazy Singleton : Double locking Singleton & : Initialization-on-demand_holder_idiom singleton

    Have a look at below code:

    public final class Singleton{
        private static final Singleton instance = new Singleton();
    
        public static Singleton getInstance(){
            return instance; 
        }
        public enum EnumSingleton {
            INSTANCE;   
        }   
        public static void main(String args[]){
            System.out.println("Singleton:"+Singleton.getInstance());
            System.out.println("Enum.."+EnumSingleton.INSTANCE);
            System.out.println("Lazy.."+LazySingleton.getInstance());
        }
    }
    final class LazySingleton {
        private LazySingleton() {}
        public static LazySingleton getInstance() {
            return LazyHolder.INSTANCE;
        }
        private static class LazyHolder {
            private static final LazySingleton INSTANCE = new LazySingleton();
        }
    }
    

    Related SE questions:

    What is an efficient way to implement a singleton pattern in Java?

    Query 2:

    One Singleton instance is created per ClassLoader. If you want to avoid creation of Singleton object during Serializaiton, override below method and return same instance.

    private Object readResolve()  { 
        return instance; 
    }
    

    Query 3:

    To achieve a cluster level Singleton among multiple servers, store this Singleton object in a distributed caches like Terracotta, Coherence etc.

提交回复
热议问题