Friday, March 9, 2012

Singleton pattern

Singleton pattern


In software engineering, the singleton pattern is a design pattern used to implement the mathematical concept of a singleton, by restricting the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects.
There is criticism of the use of the singleton pattern, as some consider it an anti-pattern, judging that it is overused, introduces unnecessary restrictions in situations where a sole instance of a class is not actually required, and introduces global state into an application.[1][2][3][4][5][6]
In C++ it also serves to isolate from the unpredictability of the order of dynamic initialization, returning control to the programmer.

Common uses

  • The Abstract Factory, Builder, and Prototype patterns can use Singletons in their implementation.
  • Facade Objects are often Singletons because only one Facade object is required.
  • State objects are often Singletons.
  • Singletons are often preferred to global variables because:
    • They don't pollute the global name space (or, in languages with namespaces, their containing namespace) with unnecessary variables.[7]
    • They permit lazy allocation and initialization, whereas global variables in many languages will always consume resources.
    • Structure

      Singleton UML class diagram.svg

      Implementation

      Implementation of a singleton pattern must satisfy the single instance and global access principles. It requires a mechanism to access the singleton class member without creating a class object and a mechanism to persist the value of class members among class objects. The singleton pattern is implemented by creating a class with a method that creates a new instance of the class if one does not exist. If an instance already exists, it simply returns a reference to that object. To make sure that the object cannot be instantiated any other way, the constructor is made private. Note the distinction between a simple static instance of a class and a singleton: although a singleton can be implemented as a static instance, it can also be lazily constructed, requiring no memory or resources until needed. Another notable difference is that static member classes cannot implement an interface, unless that interface is simply a marker. So if the class has to realize a contract expressed by an interface, it really has to be a singleton.
      The singleton pattern must be carefully constructed in multi-threaded applications. If two threads are to execute the creation method at the same time when a singleton does not yet exist, they both must check for an instance of the singleton and then only one should create the new one. If the programming language has concurrent processing capabilities the method should be constructed to execute as a mutually exclusive operation.
      The classic solution to this problem is to use mutual exclusion on the class that indicates that the object is being instantiated.

      Example

      The Java programming language solutions provided here are all thread-safe but differ in supported language versions and lazy-loading. Since Java 5.0, the easiest way to create a Singleton is the enum type approach, given at the end of this section.

      Lazy initialization

      public class Singleton {
              private static Singleton _instance = null;
       
              private Singleton() {   }
       
              public static synchronized Singleton getInstance() {
                      if (_instance == null) {
                              _instance = new Singleton();
                      }
                      return _instance;
              }
      }
      

      Traditional simple way

      This solution is thread-safe without requiring special language constructs, but it may lack the laziness of the one above. The INSTANCE is created as soon as the Singleton class is initialized. That might even be long before getInstance() is called. It might be (for example) when some static method of the class is used. If laziness is not needed or the instance needs to be created early in the application's execution, or your class has no other static members or methods that could prompt early initialization (and thus creation of the instance), this (slightly) simpler solution can be used:
      public class Singleton {
              private static final Singleton instance = new Singleton();
       
              // Private constructor prevents instantiation from other classes
              private Singleton() { }
       
              public static Singleton getInstance() {
                      return instance;
              }
      }
      


      For More Details Please Visit: 

      http://en.wikipedia.org/wiki/Singleton_pattern


No comments:

Post a Comment