Wednesday, August 1, 2007

Singleton Pattern in Java

Design patterns are descriptions of problems and possible ways of their solving during object-oriented design (OOD).
Maybe the most popular design pattern is Singleton Pattern. It is used to guarantee that there will be only one instance of particular object in the application. The realization of this pattern can be useful while creating Connection Pool, Factory, Configuration Manager, etc.
In this article you will find basic description of this pattern and the example of its practical usage (in Java).
Look through the following code:

public class Singleton {
private static Singleton _instance = null;

private Singleton() {}

public synchronized static Singleton getInstance() {
if (_instance == null)
_instance = new Singleton();
return _instance;
}
}

The constructor of this class has to be declared as private. This modificator with the help of getInstance method prevents user from creating several instances of class. So, we can add the final modificator to the class declaration.
As mentioned above, getInstance() method will create the only one instance of Singleton class. This method is synchronized one! This limitation is used to guarantee that in multi-threaded environment there would be only one instance of Singleton class as well as in the single-threaded application.
We can get rid of synchronized keyword. In order to do that the _instance field must be initialized like this:

private static Singleton _instance = new Singleton(),

Of course, the “if” construction is not critical in this case.


I use implemetation of this pattern while working with project configuration. For example, the configuration file “props.txt” consists of properties set.
Consider the following code:

import java.util.*;
import java.io.*;

public class Configuration {
private static Configuration _instance = null;

private Properties props = null;

private Configuration() {
props = new Properties();
try {
FileInputStream fis = new FileInputStream(new File(“props.txt”));
props.load(fis);
}
catch (Exception e) {
// catch Configuration Exception right here
}
}

public synchronized static Configuration getInstance() {
if (_instance == null)
_instance = new Configuration();
return _instance;
}

// get property value by name
public String getProperty(String key) {
String value = null;
if (props.containsKey(key))
value = (String) props.get(key);
else {
// the property is absent
}
return value;
}
}

Use the following code to get the value for the specified property:

String propValue = Configuration.getInstance()
.getProperty(propKey).

Also you can provide some useful constants for your properties:

public static final String PROP_KEY = “propKey”,

and get their values in such a way:

String propValue = Configuration.getInstance()
.getProperty(Configuration.PROP_KEY).

That’s all. Best regards.


Technorati Tags: , ,

2 Comments:

Qrilka said...

You can also use lazy loading using private inner class a.k.a SingletonHolder

Anonymous said...

"It is used to guarantee that there will be only one instance of particular object in the application."

That is incorrect. A singleton is only single for each ClassLoader.