Singleton
A singleton in Java is a class for which only one instance can be created provides a global point of access this instance. The singleton pattern describe how this can be archived.
Singletons are useful to provide a unique source of data or functionality to other Java Objects. For example you may use a singleton to access your data model from within your application or to define logger which the rest of the application can use.
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; } }
Comments
Post a Comment
Please post comments here:-)