What is a Singleton?
A Singleton is a pattern that ensures that a class has only one instance and provides global access to it.
Imagine we have to access our database, instead of opening a connection for each call to our DB, we could use the singleton pattern to return the same DB instance.
Let’s see how to do this manually and then let’s see the magic of Ruby:
The previous code makes the constructor private so it’s impossible to create multiple instances, instead we create a custom method that returns the cached instance.
Now comes the magic! 🪄 Ruby has already a module for singletons, so you can simplify the previous code to:
This and the previous code are the same.
What you saw is a simple example to understand Singletons. For multithread apps, we should implement a thread-safe approach.