Wednesday, August 5, 2015

Singleton object creation

1 ) Singleton with eager loading

import java.io.Serializable;
import java.lang.reflect.Constructor;

public class SingletonTest implements Serializable {

private static final long serialVersionUID = 5287483952638645154L;
private final static SingletonTest INSTANCE = new SingletonTest();

private SingletonTest() {
if (INSTANCE != null) {
throw new IllegalStateException("Inside SingletonTest(): SingletonTest " + "instance already created.");
}
System.out.println("Inside SingletonTest(): Singleton instance is being created.");
}

public static SingletonTest getInstance() {
return INSTANCE;
}

@Override
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}

// This method is called immediately after an object of this class is
// deserialized.
protected Object readResolve() {
// Instead of the object we’re on, return the class variable singleton
return INSTANCE;
}
}

To test this use given main method

public static void main(String[] args) {
//System.out.println(SingletonEnum.INSTANCE);
try {
System.out.println("Inside main(): Getting the singleton instance using getInstance()...");
System.out.println(SingletonTest.getInstance());
Class clazz = SingletonTest.class;
Constructor cons = clazz.getDeclaredConstructor();
cons.setAccessible(true);
SingletonTest s2 = cons.newInstance();
System.out.println(s2);

}
catch (Exception e) {
e.printStackTrace();
}
}

2) Singleton with Lazy Loading
package com;

public class SingletonLazy {
private SingletonLazy() {
}
private static SingletonLazy INSTANCE = null;
public static SingletonLazy getInstance() {
if (INSTANCE == null) {
synchronized (SingletonLazy.class) {
if (INSTANCE == null) {
INSTANCE = new SingletonLazy();
}
}
}
return INSTANCE;
}
}

3) Singleton with Enum
public enum SingletonEnum {
INSTANCE;

private SingletonEnum() {
System.out.println("Here");
}
}

No comments:

Post a Comment