LibraryAbout

๐Ÿ”’ Exploring the Singleton Design Pattern in Ruby


author

Author: David Martinez

Created: November 5, 2024 - Updated: November 5, 2024

Read Time: 10 min

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.

UML Diagram

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

๐Ÿ”น The Singleton class controls access to the single instance.

๐Ÿ”น The self.instance 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

# 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

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!

  • Design Patterns: Elements of Reusable Object-Oriented Software
  • Head First Design Patterns: A Brain-Friendly Guide
  • Code example

๐Ÿ’ป You can find this and other design patterns here ๐Ÿ“š