gpt4 book ai didi

java - 应用程序属性作为静态变量或带有单例的实例变量

转载 作者:行者123 更新时间:2023-12-01 11:46:43 25 4
gpt4 key购买 nike

我需要将应用程序属性从 .properties 文件读取到一个类,该类应作为应用程序属性的单点。对于这样的类,推荐的方法是什么:将这些属性定义为静态变量或具有单例模式的实例变量?

我有一个myapp.properties 文件,格式为key=value。假设此文件中定义了 2 个应用程序属性:

Company=ABC
BatchSize=1000

在应用程序启动时,我将将此文件读入类ApplicationProperties。每当我需要使用应用程序属性时,我都会使用此类。

我有两个选择:

选项 1:将应用程序属性定义为静态变量:

public class ApplicationProperties {
private static String COMPANY;
private static int BATCH_SIZE;

static {
// read myapp.properties file and populate static variables COMPANY & BATCH_SIZE
}

private ApplicationProperties() {}

public static String getCompany() {
return COMPANY;
}
public static int getBatchSize() {
return BATCH_SIZE;
}
}

选项 2:将应用程序属性定义为实例变量:

public class ApplicationProperties {
private static ApplicationProperties INSTANCE = new ApplicationProperties();

private String company;
private int batchSize;

private ApplicationProperties() {
// read myapp.properties file and populate instance variables company & batchSize
}

public static ApplicationProperties getInstance() {
return INSTANCE;
}

public String getCompany() {
return this.company;
}
public int getBatchSize() {
return this.batchSize;
}
}

对于选项 1,我将通过以下方式访问:

ApplicationProperties.getCompany();
ApplicationProperties.getBatchSize();

对于选项 2,我将通过以下方式访问:

ApplicationProperties.getInstance().getCompany();
ApplicationProperties.getInstance().getBatchSize();

哪个更好?为什么?

如果此问题之前已得到解答,请指出答案。

谢谢

最佳答案

选项 2 稍微复杂和冗长,但没有提供任何优势,因此选项 1 是更好的设计。

恕我直言,这不是“基于意见”。

关于java - 应用程序属性作为静态变量或带有单例的实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29084544/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com