本文介绍了具有延迟加载功能的单元素枚举类型单调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了许多有关在Java中实现单调模式的不同风格的论坛和帖子,似乎枚举是在Java中实现单调模式的最佳方法!
我想知道如何使用Java枚举在具有延迟加载功能的Java 中实现SingleTone模式。因为枚举只是类。第一次使用类时,它会由JVM加载并完成其所有静态初始化。枚举成员是静态的,所以它们都将被初始化。

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 wonder how can i use Java Enum to implement SingleTone pattern in java with lazy-loading capability. since Enums are just classes. The first time a class is used, it gets loaded by the JVM and all of its static initialization is done. the enum members are static , so they're all going to be initialized.

有人知道我如何在延迟加载支持下使用枚举吗?

推荐答案

您阅读的消息源说这是做懒惰单身人士的最简单方法的原因是它应该可以工作。试试这个:

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.

这篇关于具有延迟加载功能的单元素枚举类型单调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 23:03