Alternative implementation for Singleton Class

In previous posts on Singleton Designing pattern I have explained one of the way of implementing and solving concurrency issue. Singleton pattern insures that only one instance of the class should be available throughout the application context. There is an alternative implementation for insuring the same functionality that is nothing but “a class with all public static methods”.

A static method can be accessed directly by Class name without any class instance. It will serve same purpose as Singleton Class, means it shares only one state across the application.

Here is a sample implementation

import java.util.*;
class SingletonMap 
{
	private static Map<String,String> map;
	static {
		map = new HashMap<String,String>();
	}
	public static String getValue(String key){
		return map.get(key);
	}
	public static void putValue(String key, String value){
		map.put(key,value);
	}
}

Here the SingletonMap class with all methods declared as “static” and private static member variable to store data

Comments

Popular posts from this blog

State Design Pattern by Example

Eclipse command framework core expression: Property tester

Composite Design Pattern by example