Skip to content

Instantly share code, notes, and snippets.

@FlorianWolters
Created May 31, 2012 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FlorianWolters/2843916 to your computer and use it in GitHub Desktop.
Save FlorianWolters/2843916 to your computer and use it in GitHub Desktop.
Demonstration of the Singleton design pattern in Java.
package de.florianwolters.pattern.singleton;
/**
* Demonstration of the <i>Singleton</i> design pattern in Java.
*
* This is the correct implementation of the <i>Singleton</i> creational design
* pattern in the Java programming language.
*
* - Thread-safe without special language constructs (e.g.
* <tt>synchronized</tt> or <tt>volatile</tt>).
* - Prevents cloning of an instance via the <tt>Object.clone()</tt> method.
*
* @author Florian Wolters <wolters.fl@gmail.com>
*/
final public class Singleton {
// Declaring the class as "final" is required since one subclass would lead
// to unexpected behaviour.
/**
* Returns the <i>Singleton</i> instance of this class.
*
* @return The <i>Singleton</i> instance.
*/
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
/**
* Holds the <i>Singleton</i> instance of the class {@link Singleton}.
*
* The class {@link SingletonHolder} is loaded on the first execution of the
* method {@link Singleton.getInstance()} or the first access to the
* property {@link SingletonHolder.INSTANCE}.
*/
private static class SingletonHolder {
/**
* The <i>Singleton</i> instance of the class {@link Singleton}.
*/
private static final Singleton INSTANCE = new Singleton();
/**
* Private constructor.
*/
private SingletonHolder() {
}
}
/**
* Throws a CloneNotSupportedException to prevent cloning of an instance of
* this class.
*
* @return Never. Always throws a CloneNotSupportedException.
* @throws CloneNotSupportedException Always.
*/
@Override
final public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
/**
* Protected constructor to prevent creating a new instance of this class
* via the <tt>new</tt> operator.
*/
protected Singleton() {
// The constructor could also be declared with the visibility "private".
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment