如何初始化基于Java枚举的Singleton? [英] How to initialize Java enum based Singleton?
问题描述
我已经开始编写代码了,但我不知道我是否正确地做。你能帮我执行这个单身吗?
public enum BitCheck {
INSTANCE;
private static HashMap< String,String> props = null;
public synchronized void initialize(HashMap< String,String> properties){
if(props == null){
props = properties;
}
}
public boolean isAenabled(){
returnY.equalsIgnoreCase(props.get(A_ENABLED));
}
public boolean isBenabled(){
returnY.equalsIgnoreCase(props.get(B_ENABLED));
}
}
完全可以为枚举
创建构造函数:
public枚举BitCheck {
INSTANCE;
BitCheck(){
props = new HashMap< String,String>();
}
private final Map< String,String>道具;
// ..
}
请注意:
-
道具
字段可以是final(我们喜欢final
) -
道具
不必是static
- 构造函数被自动和热切地称为
注意到最后一点。由于$ {code>枚举 -include是在加载枚举BitCheck
类时被创建的,所以您无法将任何参数传递给构造函数。当然你可以通过 INSTANCE
声明:
public enum BitCheck {
INSTANCE(new HashMap< String,String>());
BitCheck(最终的Map< String,String>道具){
this.props =道具;
}
但这没有什么区别,对吧?你想实现什么?也许你真的需要懒惰初始化的单身吗?
What is the proper way to initialize java enum based singleton, if I have to initialize it before I can use the object.
I have started writing the code , but I am not sure if I am doing it right. Could you help me to implement this singleton correct for me?
public enum BitCheck {
INSTANCE;
private static HashMap<String, String> props = null;
public synchronized void initialize(HashMap<String, String> properties) {
if(props == null) {
props = properties;
}
}
public boolean isAenabled(){
return "Y".equalsIgnoreCase(props.get("A_ENABLED"));
}
public boolean isBenabled(){
return "Y".equalsIgnoreCase(props.get("B_ENABLED"));
}
}
It's perfectly possible to create constructor for enum
:
public enum BitCheck {
INSTANCE;
BitCheck() {
props = new HashMap<String, String>();
}
private final Map<String, String> props;
//..
}
Note that:
props
field can be final (we likefinal
)props
doesn't have to bestatic
- constructor is called automatically and eagerly for you
Pay attention to the last point. Since enum
-singletons are created eagerly when the enum BitCheck
class is loaded, you have no way to pass any arguments to the constructor. Of course you can through INSTANCE
declaration:
public enum BitCheck {
INSTANCE(new HashMap<String, String>());
BitCheck(final Map<String, String> props) {
this.props = props;
}
but this doesn't make any difference, right? What do you want to achieve? Maybe you actually need lazy-initialized singleton?
这篇关于如何初始化基于Java枚举的Singleton?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!