Singleton Design Pattern in Ruby

1. Definition

The Singleton Design Pattern ensures that a class has only one instance and provides a global point of access to that instance. This pattern restricts the instantiation of a class to one object.

2. Problem Statement

Imagine you want to ensure that a certain class has only one instance, maybe because it controls access to shared resources, like configuration, logging, or any other shared service. If multiple instances exist, it might lead to issues like incorrect behavior, resource overuse, or unexpected changes.

3. Solution

The Singleton pattern solves this by letting you create a class in such a way that only one instance of that class exists throughout the lifetime of an application. It also provides a point of access to the single instance, typically through a static method.

4. Real-World Use Cases

1. Database connections: Ensuring only one connection is maintained to avoid connection overhead.

2. Logging: One logger object that writes to a single log file.

3. Configuration: Using one object to store and manage application configuration.

5. Implementation Steps

1. Make the constructor of the class private to prevent external instantiation.

2. Create a class-level variable to store the singleton instance.

3. Provide a public method (commonly named instance) that returns the singleton instance.

6. Implementation in Ruby

class Singleton
  # Instance variable to store the single instance
  @@instance = nil
  # Private constructor to prevent external instantiation
  private_class_method :new
  # Method to get the singleton instance
  def self.instance
    @@instance ||= new
  # Sample method to demonstrate functionality
  def show
    "I am the Singleton!"
# Client code
singleton_1 = Singleton.instance
singleton_2 = Singleton.instance
puts "Are both instances the same? #{singleton_1 == singleton_2}"


I am the Singleton!
Are both instances the same? true


1. The Singleton class has a class-level variable @@instance to store the singleton instance.

2. The new method is made private to prevent external instantiation.

3. The self.instance method checks if @@instance is already initialized. If not, it creates an instance. If it is, it returns the existing instance.

4. In the client code, we fetch two instances using Singleton.instance and check if they are the same. They are, confirming the Singleton pattern's working.

7. When to use?

Use the Singleton pattern when:

1. You want to ensure a class only has one instance.

2. The single instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.

3. You want to control access to shared resources.