Monday, 18 April 2016

Singleton pattern - Creational


  • Create an object and make sure that only single object gets created
  • One instance of a class or one value accessible globally in an application.
  • Ensures that only one instance of a class is created and provides a global access point to the object.
 
         


Where to use
  • When we are sure that only one instance of a class is created
  • When the instance must be available through all the code
  • Ensure unique instance by defining class final to prevent cloning

Use cases

Example 1 (Lazy loading)
  • Class Singleton having an object of same type as the class (Singleton) and a private constructor
  • A static method to check null object and create a new object.
  • Client can call static method of the Singleton class to get the object.

Example 2 (Eager/Early loading)
  • Class Singleton having an object of same type instantiated using new operator and a private constructor
  • A static method to return the object.
  • Client can call static method of the Singleton class to get the object.


Example of usage
  • Logger Classes
  • Configuration Classes
  • Accesing resources in shared mode
  • A File system 
  • A Window manager
  • A printer spooler
  • A Test engineAn Input/Output socket and etc. 
  • Implementing other patterns : 
    • Factories
    • Abstract Factories

No comments:

Post a Comment

Note: only a member of this blog may post a comment.