简体   繁体   English

Initialization On Demand Holder 习惯用法

[英]Initialization On Demand Holder idiom

This is the implementation mostly seen on the web这是网络上最常见的实现

private static class LazySomethingHolder {
  public static Something something = new Something();
}

public static Something getInstance() {
  return LazySomethingHolder.something;
}

Is the following simpler variation correct, if not what is wrong with it?以下更简单的变体是否正确,如果不是,它有什么问题? Is the problem specific to java or also present in C++?问题是特定于 Java 还是 C++ 中也存在?

public static Something getInstance() {
  private static Something something = new Something();
  return something;
}

You cannot have static local variables in Java. Java 中不能有静态局部变量。

Simpler alternatives are更简单的选择是

private static final Something something = new Something();

public static Something getInstance() {
  return something;
}

or my preference if for.或者我的偏好。

enum Something {
    INSTANCE;
}

The only problem with these patterns is that if you have multiple instances you want lazily loaded, you need to have a class each, or loading one will mean loading them all.这些模式的唯一问题是,如果您想要延迟加载多个实例,则每个实例都需要有一个类,否则加载一个将意味着加载所有实例。

Java (unlike c++) doesn't have local static variables, so what you describe is simply not possible. Java(与 C++ 不同)没有局部静态变量,因此您所描述的根本不可能。 In c++ you would most likely write (known as meyer singleton):在 C++ 中,您很可能会编写(称为 meyer singleton):

public static Something& getInstance() {
    static Something something{};
    return something;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Singleton使用“按需初始化持有人惯用语” - Singleton using “Initialization-on-demand holder idiom” 初始化按需持有人习语的疑问 - Doubts in Initialization-on-demand holder idiom 正确实施按需初始化持有人习惯用法 - Correct implementation of initialization-on-demand holder idiom 点播初始化持有人成语能否导致部分创建的对象? - Can Initialization-on-demand holder Idiom result in a partially created object? 初始化按需持有者惯用线程安全,没有最终修饰符 - Is Initialization On Demand Holder idiom thread safe without a final modifier 按需初始化持有人习惯用法-何时加载类? - Initialization-on-demand holder idiom - When are classes loaded? 如果参数化,按需初始化持有人习惯仍然安全吗? - Is initialization-on-demand holder idiom still safe if parameterized? 延迟加载 singleton:双重检查锁定与按需初始化持有人习惯用法 - Lazy-loaded singleton: Double-checked locking vs Initialization on demand holder idiom Initialization on demand holder Idiom 如何确保只创建“单个”实例? - How does Initialization on demand holder Idiom ensures only "single" instance is created ever? 如何对按需初始化持有者实例的字段进行垃圾收集/清除? - How to garbage collect/clear fields of initialization-on-demand holder instance?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM