Java Singleton Design Pattern : Questions

后端 未结 11 682
渐次进展
渐次进展 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:37

    Singleton is a creational design pattern.

    Intents of Singleton Design Pattern :

    • Ensure a class has only one instance, and provide a global point of access to it.
    • Encapsulated "just-in-time initialization" or "initialization on first use".

    I'm showing three types of implementation here.

    1. Just in time initialization (Allocates memory during the first run, even if you don't use it)

      class Foo{
      
          // Initialized in first run
          private static Foo INSTANCE = new Foo();
      
          /**
          * Private constructor prevents instantiation from outside
          */
          private Foo() {}
      
          public static Foo getInstance(){
              return INSTANCE;
          }
      
      }
      
    2. Initialization on first use (or Lazy initialization)

      class Bar{
      
          private static Bar instance;
      
          /**
          * Private constructor prevents instantiation from outside
          */
          private Bar() {}
      
          public static Bar getInstance(){
      
              if (instance == null){
                  // initialized in first call of getInstance()
                  instance = new Bar();
              }
      
              return instance;
          }
      }
      
    3. This is another style of Lazy initialization but the advantage is, this solution is thread-safe without requiring special language constructs (i.e. volatile or synchronized). Read More at SourceMaking.com

      class Blaa{
      
          /**
           * Private constructor prevents instantiation from outside
           */
          private Blaa() {}
      
          /**
           * BlaaHolder is loaded on the first execution of Blaa.getInstance()
           * or the first access to SingletonHolder.INSTANCE, not before.
           */
          private static class BlaaHolder{
              public static Blaa INSTANCE = new Blaa();
          }
      
          public static Blaa getInstance(){
              return BlaaHolder.INSTANCE;
          }
      
      }
      

提交回复
热议问题