Thursday, January 8, 2009

Project Properties Holder - Singleton Design Pattern Example

A very common requirement in most of the project is managing project specific properties. Certain properties that are required at various points of flow in a project. Mostly people would like to have a solution in which to change these properties they dont have to dig out the code and change the values. Instead they would like to have some file external to the code, so that anybody with or without knowledge of code can change it. A few examples for such properties can be:

a) A project connects to a 3rd party, one may like to store the URL for the connection in a properties file.

b) A project generates a output file, one may like to store the prefix or naming convention pattern in the properties file.

There can be many more examples. Now we need to look out for a solution so that we have single point to fetch these properties. The answer comes from Singleton design pattern.

Create a singleton class PropertiesHolder.java as shown below:

import java.io.IOException;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class PropertiesHolder
{
private final Log log = LogFactory.getLog(PropertiesHolder.class);
private Properties properties = null;
private static PropertiesHolder holder = null;


public static PropertiesHolder getInstance()
{
if(holder == null)
{
holder = new PropertiesHolder();
holder.init();
}
return holder;
}
private PropertiesHolder()
{

}
private synchronized void init()
{
if(properties == null)
{
try
{
properties = new Properties();
properties.load(PropertiesHolder.class.getResourceAsStream("/project.properties"));
}
catch (IOException e)
{
log.error("Error loading runtime properties file.", e);
}
}
}

public String getProperty(String propertyName)
{
return properties.getProperty(propertyName).trim();
}
}

Project properties will be loaded once when first call is made to get a property. Any properties that are required to be changed are to be changed in project.properties file.

You may like to have a method to set property as well, the set property method will be required to update the Properties object and write that to file as well. In case the number of properties are too many and required to managed by an Admin, you can provide a UI over it as well.

No comments: