Singleton Design Pattern in Java

April 25 2010Not Commented

Categorized Under: Java

Imagine you would like to use a single connection object for database operations. Rather than creating multiple connection objects by different clients, you may use singleton object which ensures that only a single connection object is created. The class definition for singleton is given below.

 public class Connection {
 
	private static Connection connection=new Connection();
 
	//constructor
	private Connection(){
 
	}
 
	//public static method
	public static Connection getInstance(){
		return connection;
	}
 
}

Here the constructor is declared as private so that the class could not be initialized from outside. Also a static Connection object is initialized. There is a public static method getInstance() which returns connection object.  Since connection variable is declared as static, the pattern always ensure that single connection object is always created for multiple thread access. In client code, you can always access Connection object as,

Connection connection=Connection.getInstance();

Singleton design pattern is so easy to digest and implement!

cheers,

Leave a Reply

*