Design Pattern (Part 01) — Singleton Pattern

Intent

Problem

Discussion

Benefits

  • Controlled access to a single instance
  • Reduced number of objects
  • Allows refinement of operations and representations

Drawback

  • Considered as anti-pattern by many
  • Misused to situations where a single instance of a class might not be required

Implementations

  • Eager Initialization
  • Eager Initialization with static block
  • Lazy Initialization
  • Thread Safe Lazy Initialization
  • Double Check Lazy Initialization
  • Bill Pugh Implementation
  • Singleton with Single Instance Enum

Structure

Checklist

  1. Define a private static attribute in the "single instance" class.
  2. Define a public static accessor function in the class.
  3. Do “lazy initialization” (creation on first use) in the accessor function.
  4. Define all constructors to be protected or private.
  5. Clients may only use the accessor function to manipulate the Singleton.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Arun prashanth

Arun prashanth

Software Engineer at Virtusa (Pvt) Ltd.