Is Singleton Pattern is bad as many told?

Ishan Liyanage
CodeX
Published in
5 min readAug 28, 2021

--

Before we discuss its pros and cons and whether it is bad as many people told, let recall what is Singleton Pattern.

What is the Singleton Pattern?

Intent of the Singleton pattern is to ensure a class has only one instance and provide a global point of access to it. But what problem will address in the case will have only one instance of object in our app.

In some cases, we do not need to create a new instance of the class each time we need. Imagine below simple example.

We have a type called order management service. The objective of this class is that it can place order and we really do not need to create multiple objects of the same type because simply we do not need it. What we need is just the behavior of placing the order. This behavior can be executed by one single object in the application during the runtime. We will save some memory in heap by not creating new object each new time we need it. In this case we will not create millions of such objects and we just create only one object.

e.g.

public class OrderManagementService {  private static OrderManagementService instance;  private OrderManagementService() { }  public static synchronized…

--

--

Ishan Liyanage
CodeX
Writer for

Passionate Technical Lead, Senior Software Developer and free and open source software advocate. Based in Singapore.