JAVA Implementation of Singleton

Source: Internet
Author: User

Http://radio-weblogs.com/0122027/stories/2003/10/20/implementingTheSingletonPatternInJava.html

Implementing the Singleton pattern in Java

This is a copy of a 8 August 1998 article I had originally published on my tripod site, which strangely seems to still get a number of hits. I 've moved it here as a step toward shutting down that site.

Sometimes it is necessary, and it is often sufficient, to create a single instance of a given class. this has advantages in memory management, and for Java, in garbage collection. moreover, restricting the number of instances may be necessary or desirable
For logical ical or business reasons -- for example, we may only want a single instance of a pool of database connections.

A simple approach to this situation is to useStaticMembers and methods for the "Singleton" functionality. For these elements, no instance is required. The class can be madeFinalWith
APrivateConstructor in order to prevent any instance of the class from being created.

Unfortunately, this "static-singleton" approach falls short on several counts:

  1. We may require run-time information to prepare the static-singleton for use. it may be awkward to accomplish this -- I. E ., we must insure that the static-Singleton is properly initialized before each use. this greatly increases the coupling between the static-singleton
    Utility and its clients.
  2. Methods that areStaticCannot be usedImplementAnInterface. Hence we lose a great deal of the power of Java'sInterfaceEntity.
  3. All references to the singleton must be hard-coded with the name of the class. Hence there is no meaningful way to overrideStaticMethods. In other words, allStaticMethods may
    As well beFinal.

TheSingletonPattern, as described in the gang-of-four'sDesign Patterns, Mitigates the first and second problem by creatingStaticWrapper around a reference to an instance
OfSingletonClass. Here's a Java implementation of their example, which uses static methods in the class itself as the "Singleton-wrapper ".

/** * A utility class of which at most one instance * can exist per VM. * * Use Singleton.instance() to access this * instance. */public class Singleton {   /**    * The constructor could be made private    * to prevent others from instantiating this class.    * But this would also make it impossible to    * create instances of Singleton subclasses.    */   protected Singleton() {     // ...   }    /**    * A handle to the unique Singleton instance.    */   static private Singleton _instance = null;    /**    * @return The unique instance of this class.    */   static public Singleton instance() {      if(null == _instance) {         _instance = new Singleton();      }      return _instance;   }     /. ...additional methods omitted...}

If run-time information is required, it can be determined insidePrivateConstructor. For the subclassing issue, the gof describe a second approach that uses a registry, which is essentialStaticHash-table
For mapping keysSingletonInstances. This allows us to subclassSingleton, As long as we know which specific subclass we want to use at a given point in the Code. Here's a Java implementation:

import java.util.Hashtable; /** * Use Singleton.instance(String) to access a given * instance by name. */public class Singleton {   static private Hashtable _registry = new Hashtable();     // A static initializer that creates an instance of   // this class and adds it to the registry when   // the byte-code for this class is first loaded   static {      Singleton foo = new Singleton();      _registry.put(foo.getClass().getName(),foo)   }   /**    * The constructor could be made private    * to prevent others from instatiating this class.    * But this would also make it impossible to    * create instances of Singleton subclasses.    */   protected Singleton() {     // ...   }     /**    * @return The unique instance of the specified class.    */   static public Singleton instance(String byname) {      return (Singleton)(_registry.get(byname));   }    // ...additional methods omitted...}

While this approach allows us to subclass the rootSingletonClass, clients still must know which subclass (by name) They want to access. (Note that we need not use the name of the class as the key to the hashtable,
Clients must still choose which instance to request at run-time .) in other words, this addresses the first and second problems, but not the third, unless a parameter is used to hold the name of the class to reference. we wowould like to reduce this coupling.

In addition, the Registry strategy suffers from a weaker form of the drawback noted by the gof, namely that an instance of all Singleton classes above the chosen subclass is automatically created, whether or not it is actually used.

I prefer an alternate implementation, which frees clients from the responsibility of determining which subclass to reference, although this demo-must be made at some prior point in the code. (A compile-time or run-time default can easily be provided,
And the subclass to use can be dynamically altered at run-time .)

First, we createInterfaceFor objects that create instances ofSingletonClass. This is essential a combination ofAbstract Factory,Factory methodAndFunctorPatterns
In the gof book.

/** * An interface defining objects that can create Singleton * instances. */public interface SingletonFactoryFunctor {   /**    * @return An instance of the Singleton.    */   public Singleton makeInstance();}

Second, we create static wrapper forSingletonClass. Note that by separating the wrapper from the actual implementation, it is possible to both a) provide a well known access point forSingletonInstance
And B) allow greater flexiblity as to which subclass to use to create the instance. Note that the wrapper cocould actually wrap a singleton interface, rather than a concrete class.

/** * A static container for a single instance of the Singleton */final public class SingletonWrapper {   /**    * A reference to a possibly alternate factory.    */    static private SingletonFactoryFunctor _factory = null;   /**    * A reference to the current instance.    */   static private Singleton _instance = null;    /**    * This is the default factory method.    * It is called to create a new Singleton when    * a new instance is needed and _factory is null.    */   static private Singleton makeInstance() {      return new Singleton();   }   /**    * This is the accessor for the Singleton.    */   static public synchronized Singleton instance() {      if(null == _instance) {         _instance = (null == _factory) ? makeInstance() : _factory.makeInstance();      }      return _instance;   }    /**    * Sets the factory method used to create new instances.    * You can set the factory method to null to use the default method.    * @param factory The Singleton factory    */   static public synchronized void setFactory(SingletonFactoryFunctor factory) {      _factory = factory;   }    /**    * Sets the current Singleton instance.    * You can set this to null to force a new instance to be created the    * next time instance() is called.    * @param instance The Singleton instance to use.    */   static public synchronized void setInstance(Singleton instance) {      _instance = instance;   } }

Clients that use thisSingletonWrapperNeed only use something likeSingletonWrapper.instance().method().

Note that sinceSingletonWrapperIsfinal,instanceMethod
Can essentially be inlined. Hence the only real over-head here is the check if_instanceIsnull. (Even this
Cocould be removed, if we refactor the class to ensure that_instanceIs nevernull. For example:

  • Create a new instance when the class is loaded via a static initializer
  • Create a new instance when a new factory is assignedsetFactory
  • Make suresetInstanceIs never used to change_instanceTonull,
    Or create a new instance if it is)

This approach allows us to easily alter the specificSingletonInstance published -- either dynamically or at compile-time -- without altering the code that usesSingleton. Moreover,SingletonItself
Need not be aware ofSingletonFunctionality. Hence thisSingletonwrapperCan be created for pre-existing classes such as those provided with an API or framework.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.