posted Sep 12, 2011, 1:35 PM by Akrem AYADI [ updated Sep 12, 2011, 2:00 PM ]
You find bellow the two ways to implement singleton pattern:
Classic implementation
To implement singleton pattern we need to consider the following 4 steps:
Step 1: Provide a default Private constructor
public class SingletonClass { // Note that the constructor is private private SingletonClass() { // Optional Code } } |
Step 2: Create a Method for getting the reference to the Singleton Object
public class SingletonClass { private static SingletonClass instance; // Note that the constructor is private private SingletonClass() { // Optional Code } public static synchronized SingletonClass getInstance() { if (instance == null) { instance = new SingletonClass(); } return instance; } } |
Step 3: Make the Access method Synchronized to prevent Thread Problems.
public static synchronized SingletonClass getInstance() { if (instance == null) { instance = new SingletonClass(); } return instance; } |
Step 4: Override the Object clone method to prevent cloning.
@Override public Object clone() throwsCloneNotSupportedException { throw new CloneNotSupportedException(); } |
New implementation
The new implementation is easier than the first. We will just make the instance variable as private static final and update getInstance() method. This is the new class implementation:
public class SingletonClass { private static final SingletonClass instance = newSingletonClass(); // Note that the constructor is private private SingletonClass() { // Optional Code } public static SingletonClass getInstance() { return instance; } @Override public Object clone() throwsCloneNotSupportedException { throw new CloneNotSupportedException(); } } |
For performance reason, I advise you to use the new implementation J
|