在Java中单例中的Setters / Getters



我需要为一个应用程序创建工作setter/getter,它将使用几个不同的类。此类将使用一个类,该类将存储所有数据。我知道,当我使用容器类的标准构造函数时,由于容器类的不同实例,我会在空值上得到吨。

我已经在单例中创建了容器类,这很有效,但我想问一下,任何事情都可以做得更好。我的代码:

容器.java:

public class Container {
    public static final String String = "Welcome in Singleton Containern";
    private String Test = null;
    private String appName = null;
    private String appOwner = null;
    private Container(String mes) {
        System.out.println("Message from Container: " + mes);
    }
    private static class SingletonHolder {
        private final static Container INSTANCE = new Container(String);
    }
    public static Container getInstance() {
        return SingletonHolder.INSTANCE;
    }
    public String getTest() {
        return Test;
    }
    public void setTest(String test) {
        Test = test;
    }
    public String getAppName() {
        return appName;
    }
    public void setAppName(String appName) {
        this.appName = appName;
    }
    public String getAppOwner() {
        return appOwner;
    }
    public void setAppOwner(String appOwner) {
        this.appOwner = appOwner;
    }   
}

将使用此容器的示例类:

public class SecondClass {
    Container ctn = Container.getInstance();
    .
    .
    some methods...
}

现在,当我在主类中使用时,即:

ctn.setAppOwner(owner);

当我调用它时,我在任何其他类中都获得了适当的值:

Container ctn = Container.getInstance();
ctn.getAppOwner();

这是一个好方法吗?

您可以使用 ResourceBundle 概念。

public class Container {
    public static final String message = "Welcome in Singleton Containern";
    private static Container container;
    private String test = null;
    private String appName = null;
    private String appOwner = null;
    private Container(String mes) {
        System.out.println("Message from Container: " + mes);
        init();
    }
    private void init() {
        ResourceBundle myResources = ResourceBundle.getBundle("application.properties");
        this.test = myResources.getString("app.test");
        this.appName = myResources.getString("app.appName");
        this.appOwner = myResources.getString("app.appOwner");
    }
    public static Container getInstance() {
        if( container == null ) {
            synchronized( Container.class ) {
                if( container == null ) {
                    container = new Container(message);
                }
            }
        }
        return container;
    }
    public String getTest() {
        return test;
    }
    public String getAppName() {
        return appName;
    }
    public String getAppOwner() {
        return appOwner;
    }
}

然后创建名称为应用程序的属性文件,其中包含以下内容的属性。

app.test=test
app.appName=abc
app.appOwner=xyz

并将文件夹名称放在类路径中

最新更新