如何初始化基于Java枚举的Singleton? [英] How to initialize Java enum based Singleton?

查看:125
本文介绍了如何初始化基于Java枚举的Singleton?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

初始化基于java枚举的单例的正确方法是什么,如果我必须先对其进行初始化,然后才能使用该对象。



我已经开始编写代码了,但我不知道我是否正确地做。你能帮我执行这个单身吗?

  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 like final)
  • props doesn't have to be static
  • 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆