Dive into the Singleton Design Pattern

Tam Nguyen
2 min readOct 16, 2020

The Singleton pattern is one of the simplest Design Pattern in the field of Computer Science

Simply put, this pattern involves a single class which is responsible to create an object while making sure that only single object gets created.

There are many ways in which we can implement the Singleton pattern, but the following is one:

Singleton Implementation

In the book “Design Patterns: Elements of Reusable Object-Oriented Software”, the applicability of the Singleton pattern is described as follows:

  • There must be exactly one instance of a class, and it must be accessible to clients from a well-known access point.
  • When the sole instance should be extensible by sub-classing, and clients should be able to use an extended instance without modifying their code.

For the second point in the list above, there is some cases that we need to use Singleton design patterns, as following:

Singleton use-case

Although the Singleton pattern can be useful, you should not overuse it the same way you should not overuse other patterns.

In practice, the Singleton pattern is useful when exactly one object is needed to coordinate others across a system.

Warning: Often you find yourself use the Singleton pattern, it is also an indicator that you should redesign or re-evaluation your application design.

The reason is because your application is either tightly coupled or that logic is overly spread across multiple parts of a code base. Singletons can be more difficult to test due to issues ranging from hidden dependencies, the difficulty in creating multiple instances, difficulty in stubbing dependencies and so on.

To enhance your understanding about the Singleton pattern, I would recommend this article from IBM’s J.B. Rainsberger here. It is an awesome article covering the Singleton pattern that I think everyone should read about.

--

--