Design Patterns: Singleton

This is a creation pattern, that guarantees only one object instance while the life cycle project.

But why and when can I use it? For example, when you use MongoDB in your application. The MongoDB do not use the connection pool, like relational databases, so is best for it to keep the connection always open and only one for all the project. In this case, we can use the Singleton pattern to involve the class that responsible to open and return the connection for us.

Characteristics 📚

  • Has only one object instance for the project
  • In many cases, it consider an anti-pattern

Hands-on 🤓

For the class that we want to involve with Singleton Pattern, we just include a private constructor and a method that return the existing instance:

The private constructor prevents that we build the class in another location, out of it. And the method [GetInstance] guarantee the return the same instance was created, every time.

And for test our class:

The two repositories that were “created”, should have the same instance.

⚠ See the code sample on GitHub!

Conclusion ✔

  • It’s too easy to implement.
  • The same class supports a multithread environment incorrectly. Because may be create many different instance

References 📜