Singleton

Singleton is also a very popular design pattern, although when not used appropriately it does become an anti- pattern. It is used when we need an object to be unique and easily accessible from all parts of the application e.g. database handler or loggers are frequently used. It is often considered an anti-pattern because is a pain in the ass to test, but not impossible.

Let's start with the implementation and then we'll go into testing. In order to create a singleton:

  1. Create a singleton class X
  2. Make its constructor private (so that clients cannot instantiate it)
  3. Add a private static member of type X that holds a reference to the unique instance
  4. Add a public static X getInstance() method that create the unique instance (lazily and returns it)