20
Jan
Generic singleton class to instantiate objects
Step 1: Create a Singleton Generic class to instantiate objects to any user defined class
============================================================================================
import java.util.HashMap;
import java.util.Map;
public class Singleton {
private static final Singleton instance = new Singleton();
@SuppressWarnings("rawtypes")
private Map<Class, Object> mapHolder = new HashMap<Class, Object>();
private Singleton() {
}
@SuppressWarnings("unchecked")
public static <T> T getInstance(Class<T> classOf) throws InstantiationException, IllegalAccessException {
synchronized (instance) {
if (!instance.mapHolder.containsKey(classOf)) {
T obj = classOf.newInstance();
instance.mapHolder.put(classOf, obj);
}
return (T) instance.mapHolder.get(classOf);
}
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}
Step 2: create your custom class which performs some actions:
================================================================
public class Employee {
private String name;
public void setName(String nm) {
this.name = nm;
}
@Override
public String toString() {
return "Employee [name=" + name + "]";
}
}
Step 3: Client example:
==========================
package packageThree;
public class Client {
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
Employee obj = null;
obj = Singleton.getInstance(Employee.class);
obj.setName("Jackychan");
System.out.println(obj);
}
}
0 comments