Design Patterns - Singleton Pattern

singleton-pattern

Intent

Ensure a class only have one instance, and provide a global point of access to it.

Problem

Several different client objects need to refer to the same thing, and you want to ensure that you do not hav emore than one of them

Participants and Collaborators

Clients create an instance of the Singleton solely through the getInstance static method

Implementation

  • Add a private static method of the class that refers to the desired object (Initially Set to null)
  • Add a public static method that instantiates the class
  • Set the constructor’s status to be protected or private so that no one can directly instantiate the class and bypass the static constructor mechanism.
  • For case of multi-threading ensure synchronized keyword is added to the static method

Summary

  • The Singleton Pattern ensures you have at most one instance of a class in your application.
  • The Singleton Pattern also provides a global access point to that instance
  • Singleton Pattern is a convention for ensuring one and only one object is instantiated for a given class.
  • Make Private Constructor and expose class creation via static method.