DEV Community

David Martinez
David Martinez

Posted on

🔒 Exploring the Singleton Design Pattern in Ruby

Welcome! Today, let’s dive into the Singleton design pattern, a fundamental yet powerful pattern in object-oriented programming.
We’ll explore its structure, benefits, and practical use cases in Ruby.

Introducing the Singleton Pattern 🧩

The Singleton is a creational design pattern that ensures a class has only one instance and provides a global point of access to it.

This pattern is ideal for managing resources like database connections or configuration settings where only one instance is necessary.

When to Use the Flyweight Pattern?

🔸 Use Singleton when you need to control access to shared resources or ensure that only one instance of a class is used throughout the application.

🔸 This pattern is helpful for scenarios requiring centralized management, such as logging, caching, or connection pooling.

Problem Scenario

Imagine an application where multiple parts of the code access configuration settings.
Without a Singleton, you risk multiple, inconsistent instances of these settings, leading to bugs.

Solution

The Singleton pattern ensures only one instance of the configuration class exists.
Any part of the application can access this instance without worrying about duplicates.

singleton-uml-diagram

In this example, the Singleton pattern is applied to manage application configuration.

🔹 The Singleton class controls access to the single instance.

🔹 The


 method provides a global point of access, ensuring only one instance exists.

## How does it Work?
1️⃣ Define a

 ```self.instance```

 method to return the single instance of the class.

2️⃣ Use

 ```@instance ||= new```

 inside the method to create the instance if it doesn’t already exist.

3️⃣ Privateize

 ```new```

 to prevent external code from creating additional instances.

💡 Note: The Singleton pattern restricts object creation, ensuring only one instance exists.

## Why Use the Singleton Pattern?
🔒 Simplifies access to shared resources.

🔒 Reduces the risk of inconsistent states across the application.

🔒 Provides centralized control and management of instances.

🔒 Optimizes memory usage by limiting unnecessary instance creation.

## Show me the code


```python
# Singleton class for AppConfig
class AppConfig
  @instance = nil

  # Ensures only one instance of AppConfig exists
  def self.instance
    @instance ||= new
  end

  # Stores application configurations
  attr_accessor :settings

  # Sample initialization of settings
  def initialize
    @settings = { app_name: "MyApp", version: "1.0.0" }
  end

  # Prevents external instantiation
  private_class_method :new
end

# Client code
def main
  config1 = AppConfig.instance
  config2 = AppConfig.instance

  puts config1.settings  # => {:app_name=>"MyApp", :version=>"1.0.0"}
  config2.settings[:version] = "2.0.0"

  puts config1.settings  # => {:app_name=>"MyApp", :version=>"2.0.0"}
  puts config1.equal?(config2)  # => true
end

main

# Output
# {:app_name=>"MyApp", :version=>"1.0.0"}
# {:app_name=>"MyApp", :version=>"2.0.0"}
# true
Enter fullscreen mode Exit fullscreen mode

Conclusion 🔖

The Singleton pattern is a powerful tool to control resource usage by ensuring a class has only one instance.

🔺 It’s ideal for scenarios where centralized control is needed, like managing configurations.

🔺 The Singleton pattern simplifies code, minimizes memory footprint, and ensures consistency.

🔺 By implementing Singleton, you create a reliable way to manage shared resources across the application.

Join the Quest!

💻 You can find this and other design patterns here 📚

Top comments (0)