应用程序属性作为静态变量或单例实例变量

Application properties as static variables or instance variables with singleton

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

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

Company=ABC
BatchSize=1000

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

我有两个选择:

选项 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 是更好的设计。

恕我直言,这不是 "opinion-based"。