The Singleton Pattern is one of the most commonly used design patterns in Java. This design pattern is used to restrict the instantiation of a class to a single object.
By having a private default constructor for the class, other classes are not allowed to instantiate a new object of the class. A synchronized static instance class level method is used to manage the the creation of the object.
The method has to be synchronized to prevent simultaneous invocation of the static method from two or more threads.
Enough of the explanations. Let’s take a look at a sample code implementing a Singleton class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public class SingletonClass { private static SingletonClass instance = null; private SingletonClass () {} // constructor public static synchronized SingletonClass getInstance () { instance = (instance == null ? new SingletonClass() : instance; return instance; } public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } } |