lundi 16 mars 2015

Application properties as static variables or instance variables with singleton

I need to read application properties from a .properties file to a class which should work as a single point to application properties. For such a class what is the recommended way: define those properties as static variables or as instance variables with singleton pattern?


I have a myapp.properties file in format key=value. Suppose there are 2 application properties defined in this file:



Company=ABC

BatchSize=1000



On application startup I will be reading this file into a class ApplicationProperties. I will be using this class whenever I need to use application properties.


I have 2 options:


Option 1: Define the application properties as static variables:



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


Option 2: Define the application properties as instance variables:



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


For Option 1 I would be accessing this way:



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


For Option 2 I would be accessing this way:



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


Which is preferable? And why?


If this question has been answered before please point to the answer.


Thanks


Aucun commentaire:

Enregistrer un commentaire