Definition

  • A component created only once

Motivation

  • For some component, it only makes sense to have one instance of it
    • Database repository
    • Object Factory
  • Constructor call is expensive
    • Only do it once
    • Provide any one with the same instance
  • Prevent anyone from creating additional copy
  • Need to take care of lazy instantiation and thread safety

Implementation

  • Make a safe singleton:
    • Hide or delete type’s constructor, copy constructor or assignment operator
    • Create a static method that returns a reference to a static member
    • Guaranteed to be thread-safe since C++11
  • Types with hard dependencies Singleton are difficult to test
    • Cannot decouple singleton and supply a fake object
  • Consider depending on abstraction
  • Consider defining singleton lifetime using DI container

Singleton In Dependency Injection