Thread-safe Singleton

This lesson discusses correctly implementing a singleton pattern in Ruby.

We'll cover the following...

Thread-safe Singleton

You are designing a library of superheroes for a video game that your fellow developers will consume. Your library should always create a single instance of any of the superheroes and return the same instance to all the requesting consumers.

Say, you start with the class Superman. Your task is to make sure that other developers using your class can never instantiate multiple copies of superman. After all, there is only one superman!

widget

Solution

You probably guessed we are going to use the singleton pattern to solve this problem. The singleton pattern sounds very naive and simple but can be tricky to implement correctly especially in a multi-threaded environment.

First let us understand what the pattern is. A singleton pattern allows only a single object/instance of a class to ever exist during an application run. Typical uses of singleton pattern include creating objects that represent configuration data, global logging systems, and other similar structures.

Following are some of the ways of implementing the Singleton design pattern in Ruby:

Using Singleton Module

The first implementation makes use of the Singleton module offered by Ruby’s standard library. The only difference between a module and a class in Ruby is ...