# Singleton Pattern in Software Engineering

Today I learned about Singleton design pattern in Software Engineering.

And, I thought why not publish an article on it.

**What is Singleton?**

Singleton is a design pattern in Software Engineering where you can create more than one instance of a class.

**Why is it important?**

Singleton patterns are important and are quite widely used because:

\- It helps in efficient memory management.

\- Helps to share data accross multiple servers if you are scaling and have a stateful backend.

\- Ensures possible hazards if a new dev joins.

**How can it be achieved?**

While "Singleton" sounds like a heavy term, but it is just a jargon.

You can achieve it just by making the constructor private.

**Here's an example to better understand this:**

Let's say you get a lot of requests and you scale you server from one to two.

Now the 2nd server creates a "new" instance of the 'RequestCounter' class starting from zero.

![](https://d3e0luujhwn38u.cloudfront.net/resized/rHCEDxJLUhGNISKdNyeHaVc63hH-fwXifDOE_bSxRxU/s:1200/plain/s3://typefully-user-uploads/img/original/98576/484a3d27-f24a-4773-b66f-0fc91e504923.png align="left")

This means, despite the `userId = 1` having made 6 reqs in total will have two different records in two different servers.

Because, the instance created by BE1 is completely different from BE2.

Here's a better solution using singleton:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1716456478273/9c7a2496-540a-49af-90e5-32e2108008ff.png align="center")

In this solution: both the backends BE1 and BE2 share the same state of request count for the user with `id = 1` .

That's it for this one.  
  
Hope you got to learn something from this post.  
  
Share, Like and Follow.  
  
More knowledge on the way!
