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
Nice post , just to add
ReplyDeleteWhile writing Singleton class we need to consider many points e.g.
1) Lazy initialization
2) Early initialization
3) Serialization
4) Many ClassLoaders
to tackle all above problem best way is to use JAVA 5 Enum functionality and write Singleton using Enum like below.
public enum Singleton {
INSTANCE;
public static void hi(){
System.out.println("Hi");
}
}
Thanks
Javin
Why String is immutable in Java
It's been a while I didn't look at this blog, anyway thanks Javin for pointing this out. Have a nice day :)
ReplyDelete