Singleton
Singleton classes represent objects for which only one instance should exist.
Here is an article from Sun's Java Develper Connection describing them. This article, along with many others, reports many subtle problems with singletons. You should likely exercise care when using this pattern.
Example 1
This is the preferred style of implementing singletons. It uses a simple enumeration.
It has no special needs for serialization, and is immune to clever attacks.
/** Preferred style for singletons. */ public enum SantaClaus { INSTANCE; /**Add some behavior to the object. */ public void distributePresents(){ //elided } /** Demonstrate use of SantaClaus. */ public static void main(String... aArgs){ SantaClaus fatGuy = SantaClaus.INSTANCE; fatGuy.distributePresents(); //doesn't compile : //SantaClaus fatGuy = new SantaClaus(); } }
Example 2
Here is an alternate style.
If you decide that the class should no longer be a singleton, you may simply change the implementation of getInstance.
public final class Universe { public static Universe getInstance() { return fINSTANCE; } // PRIVATE // /** * Single instance created upon class loading. */ private static final Universe fINSTANCE = new Universe(); /** * Private constructor prevents construction outside this class. */ private Universe() { //..elided } }
Example 3
If the above style of singleton is to be Serializable as well, then you must add a readResolve method.
import java.io.*; public final class EasterBunny implements Serializable { public static EasterBunny getInstance() { return fINSTANCE; } // PRIVATE // /** * Single instance created upon class loading. */ private static final EasterBunny fINSTANCE = new EasterBunny(); /** * Private constructor prevents construction outside this class. */ private EasterBunny() { //..elided } /** * If the singleton implements Serializable, then this * method must be supplied. */ private Object readResolve() throws ObjectStreamException { return fINSTANCE; } }
See Also :
Would you use this technique?
|
|