Singleton Pattern in Software Engineering

Β·

2 min read

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.

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:

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!

Β