single-element enum type singletone with lazy loading capability

前端 未结 2 566
太阳男子
太阳男子 2021-01-02 09:03

I read many forums and posts about different style to implement single-tone pattern in java and seems \"Enum are the best way to implement singletone pattern in java\"!! I w

2条回答
  •  盖世英雄少女心
    2021-01-02 09:43

    The reason the source you read said it's the easiest way to do lazy singletons is because it should just work. Try this:

    public class LazyEnumTest {
      public static void main(String[] args) throws InterruptedException {
        System.out.println("Sleeping for 5 seconds...");
        Thread.sleep(5000);
        System.out.println("Accessing enum...");
        LazySingleton lazy = LazySingleton.INSTANCE;
        System.out.println("Done.");
      }
    }
    
    enum LazySingleton {
      INSTANCE;
      static { System.out.println("Static Initializer"); }
    }
    

    Here's the output I get in the console:

    $ java LazyEnumTest
    Sleeping for 5 seconds...
    Accessing enum...
    Static Initializer
    Done.
    

提交回复
热议问题