如何初始化基于Java枚举的Singleton?

jav*_*use 16 java singleton enums

如果我必须在使用该对象之前初始化它,那么初始化基于java enum的单例的正确方法是什么.

我已经开始编写代码,但我不确定我是否做得对.你能帮我实现这个单身对我来说正确吗?

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"));
    }

}
Run Code Online (Sandbox Code Playgroud)

Tom*_*icz 32

完全可以为以下内容创建构造函数enum:

public enum BitCheck {

    INSTANCE;

    BitCheck() {
        props = new HashMap<String, String>();
    }

    private final Map<String, String> props;

    //..

}
Run Code Online (Sandbox Code Playgroud)

注意:

  • props字段可以是最终的(我们喜欢final)
  • props 不一定是 static
  • 构造函数会自动为您而急切地调用

注意最后一点.由于enumenum BitCheck加载类时急切地创建了-singletons ,因此无法将任何参数传递给构造函数.当然你可以通过INSTANCE声明:

public enum BitCheck {

    INSTANCE(new HashMap<String, String>());

    BitCheck(final Map<String, String> props) {
        this.props = props;
    }
Run Code Online (Sandbox Code Playgroud)

但这没有任何区别,对吧?你想达到什么目的?也许你真的需要懒惰初始化的单身人士?

  • @java_mouse:就是这样。没有办法从外部将任何东西传递给构造函数,“枚举”单例将无济于事。 (2认同)

Ami*_*nde 5

你必须在声明中初始化它.

public enum BitCheck {
    INSTANCE;
    private final Map<String, String> props = new ConcurrentHashMap<String, String>();

    public void putAll(HashMap<String, String> map) {
        props.putAll(map);
    }
}
Run Code Online (Sandbox Code Playgroud)