Friday, January 9, 2015

Singleton java class Example

package com.singleton.pattern;

import java.io.Serializable;

public class SingletonDemo implements Cloneable, Serializable {
private static SingletonDemo instance;

/**
* Don't remove this constructor
*/
private SingletonDemo() {
// no-operation
System.out.println("SingletonDemo() created...");
}

public static SingletonDemo getInstance() {
// double-checking solution
if (instance == null) {
synchronized (SingletonDemo.class) {
System.out.println("locked..");
if (instance == null) {
instance = new SingletonDemo();
}
}
}
return instance;
}

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

protected Object readResolve() {
return instance;
}

}


No comments:

Post a Comment