Add new comment

When you still need use the singleton pattern?

The singleton pattern has come a long way since early 1990x. The programmer interview question "Write a singleton" in 1995 has evolved to "Write a lazy initialized singleton" in 2000x, and finished by "Why we do not use a singleton?" in 2010x.

Indeed, the unproved using of multiple singletons should be considered as antipattern. However, we still need singletons in some cases.

  1. There should be only one object in the program
  2. Need to access to the object from multiple parts and even layers of the program
  3. Optional: need to control the concurrent access to the shared unique resource

The usual argument against the singleton is a much harder testing as you need to include the dependency. However, you always can add testing interfaces to manipulate the singleton object and inject it explicitly.

The good examples of singleton:

  • log facility
  • database connection pool
  • application global instance or context