有些人使用枚举而不是类来创建对象并将其注入(inject)代码。例如
public enum EnumSample {
INSTANCE;
private String name = "Sample Enum";
private String version = "1";
public String getName() {
return this.name;
}
public String getVersion() {
return this.version;
}
}
在类里面:
public class MyClass {
public static void main(String[] args) {
new App();
}
}
public class App {
private EnumSample enumSample = EnumSample.INSTANCE;
public App() {
System.out.printf("%s - %s",enumSample.getName(), enumSample.getVersion());
}
}
那么它是正确的吗?因为在 Oracle 网站的 Java 文档中他们说:
From Java documents -
You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on.
我只想知道这种方式是否正确,有没有更好的模式?请考虑该版本在这里只是一个例子......
我知道 Enum 对于 Singelton 是正确的...我只是想找到不使用 Enum 的其他方法,如果有的话请与我分享...谢谢
最佳答案
enum
在 Java 中实际上有两个主要用例:
(1) 定义一组固定的常量,如 Java 文档中直接提到的那样。
(2) enum
也可用于安全地(线程)创建类的单例实例(即,无需显式使用 synchronize
等)。可以引用here关于这个问题。
在您的 EnumSample
中,您实际上是在创建 EnumSample
的一个且只有一个对象,它可以通过变量 INSTANCE
引用(用例2 以上)。
I got that Enum is correct for Singelton ones. I just want to find the other ways to do these without Enum.
在 Java 中,有几种方法可以以线程安全的方式创建单例实例,其中一种如下所示,它使用 static
final
INSTANCE
使用 private
构造函数:
public class Sample {
//Create a static final object
private static final Sample INSTANCE = new Sample();
//private constructor, so this class can't instantiated from outside
private Sample() {
}
//Use the getInstance() static method which returns same instance always
public static Sample getInstance() {
return INSTANCE;
}
private String name = "Sample Enum";
private String version = "1";
public String getName() {
return this.name;
}
public String getVersion() {
return this.version;
}
}
public class App {
public App() {
System.out.printf("%s - %s",Sample.getInstance().getName(),
Sample.getInstance().getVersion());
}
}
可以引用here了解安全创建单例的其他方法。
关于java - 使用 POJO 进行控制反转和依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41311235/