Item 3: Singleton

Although there are many ways of making a class singleton, I am going to stick to only 2 ways of making classes singleton.

Approach 1. Private Constructor
Make constructor private and expose a public static final field. The final field is initialized using the constructor which is run just once.
/**
 * Singleton using enum
 * 
 * @author lekhak.tumblr.com
 */
public class Properties {
	public static final Properties properties = new Properties();

        private Properties() { ... }

	public static Properties getInstance () {
        return properties ;
    }
}
Approach 2. Using Enum
/**
 * Singleton using enum
 * 
 * @author lekhak.tumblr.com
 */
public enum Properties {
	INSTANCE;
	
	Map properties = new HashMap();
	
	Properties() {
		properties = loadFromDB();
	}

	public Map loadFromDB() {
		//Implementation
		return new HashMap();
	}
}
**Please note that when a singleton class is made serializable, to ensure the creation of the instance only once, one has to use a readResolve method.

Advertisements

About Gaurav

I'm Gaurav; friends call me Teddy, n i'm shivi fr my family!! A java enthusiast who likes experimenting with what he knows. View all posts by Gaurav

2 responses to “Item 3: Singleton

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: