Singleton
Singleton design pattern enables us to guarantee unicity and a single entry point for services and accesses. Tipically it requires the standard contructor to be hidden in order to avoid direct instantiation, but modern frameworks use this pattern in conjunction with other creational patterns in order to ease the development of services.
Usage
Typical usage for the Singleton pattern is the management of a single centralized state with the warranty that nothing that is not part of the singleton interface will touch it.
Examples
- Angular services are (per default) singletons. These services are instantiated by the framework and can be used directly through Dependency Injection.
Specimens
15 implementationsThe Singleton pattern ensures a class has only one instance, and provides a global point of access to it. This is useful for managing resources like database connections, configuration settings, or logging services where multiple instances would be problematic or inefficient. In Dart, this is efficiently implemented using a static instance and a private constructor. The private constructor prevents external instantiation, while the static factory method instance provides controlled access to the single instance. This approach leverages Dart’s static members and constructor control for a concise and thread-safe Singleton.
/// A class representing a Singleton.
class Singleton {
// Private constructor to prevent direct instantiation.
Singleton._();
// Static instance to hold the single instance.
static final Singleton _instance = Singleton._();
// Static factory method to access the instance.
static Singleton get instance => _instance;
// Example data/method to demonstrate usage.
String data = 'Initial Data';
void updateData(String newData) {
data = newData;
}
}
// Example Usage (not part of the Singleton class itself)
void main() {
final singleton1 = Singleton.instance;
final singleton2 = Singleton.instance;
print(singleton1 == singleton2); // Output: true
singleton1.updateData('Updated Data');
print(singleton2.data); // Output: Updated Data
}
The Singleton pattern ensures a class has only one instance and provides a global point of access to it. In Scala, this is most easily achieved using the object keyword. An object automatically creates a single instance of a class and makes it accessible without needing to explicitly instantiate it. This implementation is highly idiomatic as Scala favors immutability and objects are a first-class citizen, often used for utility functions, constants, and globally accessible resources. We define our singleton as an object, allowing access to its methods and properties directly through the object’s name.
// Singleton Pattern in Scala
object Logger {
private var logEntries: List[String] = List.empty
def log(message: String): Unit = {
val entry = s"[${java.time.LocalDateTime.now()}] $message"
logEntries = entry :: logEntries
println(entry)
}
def getLogEntries(): List[String] = logEntries
}
// Usage
object Main {
def main(args: Array[String]): Unit = {
Logger.log("Application started")
Logger.log("Processing data...")
val logs = Logger.getLogEntries()
logs.foreach(println)
}
}
The Singleton pattern ensures a class has only one instance and provides a global point of access to it. This is useful for managing resources that should only exist once, like database connections or configuration settings. The PHP implementation utilizes a static method getInstance() to control instance creation, delaying instantiation until it’s first requested. A private constructor prevents direct instantiation from outside the class. This approach aligns with PHP’s ability to manage class state through static methods and properties, offering a clean and controlled way to ensure a single instance.
<?php
/**
* Singleton class.
*/
class Singleton
{
/**
* The single instance.
*
* @var Singleton|null
*/
private static ?Singleton $instance = null;
/**
* Private constructor to prevent direct instantiation.
*/
private function __construct()
{
// Initialization code here, if any
}
/**
* Get the single instance of the class.
*
* @return Singleton
*/
public static function getInstance(): Singleton
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Prevent cloning of the instance.
*/
private function __clone()
{
}
/**
* Prevent unserialization of the instance.
*/
public function __wakeup()
{
}
/**
* Example method.
*
* @return string
*/
public function doSomething(): string
{
return 'Singleton is doing something!';
}
}
// Usage:
require_once 'Singleton.php';
$instance1 = Singleton::getInstance();
$instance2 = Singleton::getInstance();
echo $instance1->doSomething() . "\n";
echo $instance1 === $instance2; // Output: 1 (true)
?>
The Singleton pattern ensures a class has only one instance and provides a global point of access to it. This is useful for managing resources like database connections, configuration settings, or a logger where multiple instances would be detrimental.
The Ruby implementation uses a class variable @@instance to store the single instance. The instance class method acts as the global access point, creating and returning the instance only if it doesn’t already exist. This utilizes Ruby’s meta-programming capabilities and inherent class-level method access, making it a concise and common approach to implementing the Singleton pattern. Defining private_class_method :new prevents direct instantiation outside the class itself.
# singleton.rb
module Singleton
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def instance
@@instance ||= new
end
private_class_method :new
end
end
class Configuration
include Singleton
def initialize
@settings = {
"api_key" => "your_api_key",
"timeout" => 30
}
end
def api_key
@settings["api_key"]
end
def timeout
@settings["timeout"]
end
end
# Example Usage:
config1 = Configuration.instance
config2 = Configuration.instance
puts config1.object_id == config2.object_id #=> true
puts config1.api_key #=> your_api_key
The Singleton pattern ensures a class has only one instance and provides a global point of access to it. This is useful for managing shared resources or configurations. In Swift, we achieve this using a static instance property and a private initializer to prevent external instantiation. The example demonstrates a Logger class that manages logging functionality throughout the application. The shared property provides access to the unique instance. This approach is idiomatic Swift, leveraging static properties for global access and controlling object creation through initializer access control.
// Logger.swift
import Foundation
class Logger {
static let shared = Logger()
private init() {
// Private initializer to prevent direct instantiation
}
func log(message: String) {
let timestamp = DateFormatter.localizedString(from: Date(), format: "yyyy-MM-dd HH:mm:ss")
print("[\(timestamp)] - \(message)")
}
}
// Usage:
// Logger.shared.log(message: "Application started")
// Logger.shared.log(message: "User logged in")
The Singleton pattern ensures a class has only one instance and provides a global point of access to it. This is useful for managing resources like database connections or configuration settings where multiple instances would be wasteful or problematic. In Kotlin, we achieve this using an object declaration. objects are inherently singletons—Kotlin guarantees only one instance exists. This approach is concise and type-safe, leveraging Kotlin’s language features to avoid the boilerplate often seen in other languages (like explicit private constructors and static instance holders). It’s a very idiomatic and preferred way to implement the Singleton pattern in Kotlin.
// SingletonLogger.kt
/**
* A singleton class that provides logging functionality.
*/
object SingletonLogger {
private val logs = mutableListOf<String>()
/**
* Adds a log message.
* @param message The message to log.
*/
fun log(message: String) {
logs.add(message)
println("LOG: $message")
}
/**
* Retrieves all logged messages.
* @return A list of log messages.
*/
fun getAllLogs(): List<String> {
return logs.toList() // Return a copy to prevent external modification
}
}
fun main() {
SingletonLogger.log("Application started")
SingletonLogger.log("Processing data...")
val allLogs = SingletonLogger.getAllLogs()
println("All Logs: $allLogs")
}
The Singleton pattern ensures a class has only one instance and provides a global point of access to it. In Rust, this is commonly achieved using static combined with lazy initialization via lazy_static. This avoids unsafe mutable global state. Our code defines a Logger struct and uses lazy_static to create a single, globally accessible instance. The log_message function allows logging through this unique instance. This approach suits Rust’s ownership and borrowing rules, and avoids data races by ensuring safe, thread-safe initialization. Using a static ensures the instance exists for the program’s duration.
use lazy_static::lazy_static;
use std::sync::Mutex;
#[derive(Debug)]
struct Logger {
log_entries: Vec<String>,
}
impl Logger {
fn new() -> Self {
Logger { log_entries: Vec::new() }
}
fn log_message(&mut self, message: String) {
self.log_entries.push(message);
println!("Logged: {}", message);
}
fn get_log_entries(&self) -> &Vec<String> {
&self.log_entries
}
}
lazy_static! {
static ref LOGGER: Mutex<Logger> = Mutex::new(Logger::new());
}
fn get_logger() -> std::sync::MutexGuard<'static, Logger> {
LOGGER.lock().unwrap()
}
fn main() {
let mut logger1 = get_logger();
logger1.log_message("This is the first log message.".to_string());
let mut logger2 = get_logger();
logger2.log_message("This is the second log message.".to_string());
let log_entries = logger2.get_log_entries();
println!("Log Entries: {:?}", log_entries);
}
The Singleton pattern ensures a class has only one instance and provides a global point of access to it. This is useful for managing resources that should be shared across the application, like database connections or configuration settings. In Go, we achieve this using a private variable to hold the instance and a public method to access it, initializing the instance if it’s not already created. This approach is idiomatic as Go doesn’t have explicit class keywords and promotes package-level access for global state, leveraging zero-value initialization and potential concurrency safety mechanisms like sync.Once.
package main
import (
"fmt"
"sync"
)
// singleton is the instance of the Singleton. It's private to enforce control.
var singleton *Singleton
var once sync.Once
// Singleton represents the Singleton object.
type Singleton struct {
data string
}
// GetInstance is the public method to access the Singleton instance.
func GetInstance() *Singleton {
once.Do(func() {
singleton = &Singleton{data: "Initial Data"}
})
return singleton
}
// GetData returns the data held by the singleton.
func (s *Singleton) GetData() string {
return s.data
}
// SetData sets the data held by the singleton.
func (s *Singleton) SetData(data string) {
s.data = data
}
func main() {
instance1 := GetInstance()
instance2 := GetInstance()
fmt.Printf("Instance 1: %p\n", instance1)
fmt.Printf("Instance 2: %p\n", instance2)
if instance1 == instance2 {
fmt.Println("Both instances are the same.")
}
instance1.SetData("Updated Data")
fmt.Println("Instance 2 Data:", instance2.GetData())
}
The Singleton pattern ensures a class has only one instance and provides a global point of access to it. This is useful for managing resources like configuration settings, logging, or database connections where multiple instances would be detrimental. The C implementation utilizes a static pointer to the single instance, initialized lazily upon the first call to a static access method. Thread safety isn’t explicitly addressed here for simplicity, but would require a mutex for production use. This approach is idiomatic C, leveraging static variables and function pointers for controlled instance creation and access.
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int data;
} Singleton;
static Singleton *instance = NULL;
Singleton *getInstance() {
if (instance == NULL) {
instance = (Singleton *)malloc(sizeof(Singleton));
if (instance == NULL) {
perror("Failed to allocate memory for Singleton instance");
exit(EXIT_FAILURE);
}
instance->data = 42; // Initialize the instance's data
printf("Singleton instance created.\n");
}
return instance;
}
void cleanupSingleton() {
if (instance != NULL) {
free(instance);
instance = NULL;
printf("Singleton instance destroyed.\n");
}
}
int main() {
Singleton *s1 = getInstance();
Singleton *s2 = getInstance();
printf("s1->data: %d\n", s1->data);
printf("s2->data: %d\n", s2->data);
if (s1 == s2) {
printf("Both pointers point to the same instance.\n");
}
cleanupSingleton();
return 0;
}
The Singleton pattern ensures a class has only one instance and provides a global point of access to it. This is useful for managing resources that should only have one controller, like a configuration manager or a logger.
The C++ implementation uses a private constructor to prevent direct instantiation. A static member function, getInstance(), is provided which creates the instance only if it doesn’t already exist, and returns a pointer to it. The instance is held as a static member. Modern C++ (C++11 and later) leverages thread safety with std::call_once to guarantee only one instance is created even in multi-threaded environments. This approach balances safety and efficiency.
#include <iostream>
#include <mutex>
#include <memory>
class Singleton {
private:
Singleton() {
std::cout << "Singleton instance created.\n";
}
~Singleton() {
std::cout << "Singleton instance destroyed.\n";
}
// Prevent copying and moving
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
Singleton(Singleton&&) = delete;
Singleton& operator=(Singleton&&) = delete;
public:
static Singleton* getInstance() {
static Singleton instance;
return &instance;
}
void doSomething() {
std::cout << "Singleton is doing something!\n";
}
};
int main() {
Singleton* instance1 = Singleton::getInstance();
instance1->doSomething();
Singleton* instance2 = Singleton::getInstance();
instance2->doSomething();
// Verify that both pointers point to the same instance
if (instance1 == instance2) {
std::cout << "Both instances are the same.\n";
}
return 0;
}
The Singleton pattern ensures a class has only one instance and provides a global point of access to it. It’s useful for managing resources like database connections or configuration settings where multiple instances would be detrimental. This C# implementation uses a static instance and a private constructor to enforce the single instance rule. The Instance property provides the global access point, and it’s lazy-initialized, meaning the instance is created only when first accessed. This approach is thread-safe in C# due to the inherent behavior of static initialization. The use of properties and a static member are standard C# conventions for achieving this.
// Singleton.cs
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton(); // Lazy initialization
// Private constructor to prevent external instantiation
private Singleton()
{
// Initialization logic here (e.g., loading configuration)
}
public static Singleton Instance
{
get
{
return instance;
}
}
public void DoSomething()
{
Console.WriteLine("Singleton is doing something!");
}
}
// Example usage
public class Example
{
public static void Main(string[] args)
{
Singleton s1 = Singleton.Instance;
Singleton s2 = Singleton.Instance;
Console.WriteLine(ReferenceEquals(s1, s2)); // Output: True
s1.DoSomething();
}
}
The Singleton pattern ensures a class has only one instance and provides a global point of access to it. This is useful for managing resources like database connections or configuration settings where only one instance should exist throughout the application. The TypeScript implementation uses a static instance property within the class to hold the single instance. The first time the getInstance method is called, it creates the instance; subsequent calls return the existing one. This approach leverages TypeScript’s class structure and static members for a type-safe and controlled instantiation.
// singleton.ts
class Singleton {
private static instance: Singleton | null = null;
private constructor(public data: string) {} // Private constructor
public static getInstance(data: string): Singleton {
if (!Singleton.instance) {
Singleton.instance = new Singleton(data);
}
return Singleton.instance;
}
public getData(): string {
return this.data;
}
}
// Example usage:
const instance1 = Singleton.getInstance("Initial Data");
const instance2 = Singleton.getInstance("Different Data"); // Ignored, instance already exists
console.log(instance1.getData());
console.log(instance1 === instance2); // true
The Singleton pattern ensures a class has only one instance and provides a global point of access to it. This is useful for managing resources like database connections or configuration settings where multiple instances would be detrimental. The JavaScript implementation uses a closure to encapsulate the instance and a static method to provide access. This approach is idiomatic because JavaScript’s flexible nature allows for this kind of self-managing object creation without strict class definitions (though a class can be used, this is a common functional style). The getInstance() method lazily initializes the instance only when it’s first requested.
// config.js
const Config = (function() {
let instance;
function createConfig(settings) {
const config = {
...settings,
get: (key) => config[key]
};
return config;
}
return {
getInstance: function(settings) {
if (!instance) {
instance = createConfig(settings);
}
return instance;
}
};
})();
export default Config;
// app.js
import Config from './config.js';
// First instance with initial settings
const config1 = Config.getInstance({ apiUrl: 'https://api.example.com', theme: 'light' });
console.log(config1.get('apiUrl')); // Output: https://api.example.com
// Second request - returns the same instance
const config2 = Config.getInstance({ apiKey: 'someKey' }); // Settings are ignored.
console.log(config2.get('apiUrl')); // Output: https://api.example.com
console.log(config1 === config2); // Output: true
//Demonstrate Config can be extended with more functions
config1.logSettings = function() {
console.log("API URL:", this.get('apiUrl'), "Theme:", this.get('theme'));
}
config1.logSettings(); //Output: API URL: https://api.example.com Theme: light
The Singleton pattern ensures a class has only one instance and provides a global point of access to it. This is useful for managing resources like database connections or configuration settings where multiple instances would be detrimental.
The Python implementation uses a class with a private class variable _instance to store the single instance. The __new__ method is overridden to control instance creation. It checks if _instance is already set; if not, it creates a new instance and stores it in _instance. Subsequent calls to the constructor return the stored instance. This approach is Pythonic as it leverages the language’s dynamic nature and avoids explicit locking mechanisms often found in other languages.
class Singleton:
"""
A Python implementation of the Singleton pattern.
"""
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls._instance
def __init__(self, value):
if not hasattr(self, 'initialized'):
self.value = value
self.initialized = True
def get_value(self):
return self.value
# Example Usage
if __name__ == "__main__":
s1 = Singleton(10)
s2 = Singleton(20) # This will return the same instance as s1
print(f"s1 value: {s1.get_value()}")
print(f"s2 value: {s2.get_value()}")
print(f"s1 is s2: {s1 is s2}")
Very simple and basic pure POJO implementation of the pattern