public class SingletonObject { //marked as private so that class can't be directly instantiated private SingletonObject() { // no code req'd } //add synchronized keyword to prevent thread making a new copy public static synchronized SingletonObject getSingletonObject() { if (ref == null) { // it's ok, we can call this constructor ref = new SingletonObject(); } return ref; } //overwrite default clone method so that this class can't be cloned public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); // that'll teach 'em } private static SingletonObject ref; }
reference : http://www.javacoffeebreak.com/articles/designpatterns/index.html