[英]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.