Singleton
Tags: beginners
Published: 2022-11-12 01:03:02

## What is Singleton?
Singleton is a creational design pattern that lets you ensure that a class has only one instance, while providing a global access point to this instance.

Class is defined in such a way that only one instance of the class is created in the complete execution of a program or project.
It is used where only a single instance of a class is required to control the action throughout the execution.
A singleton class shouldn’t have multiple instances in any case and at any cost. Singleton classes are used for logging, driver objects, caching and thread pool, database connections.

---

## An implementation of singleton class should have following properties
- **It should have only one instance**: This is done by providing an instance of the class from within the class. Outer classes or subclasses should be prevented to create the instance. This is done by making the constructor private in java so that no class can access the constructor and hence cannot instantiate it.
- **Instance should be globally accessible**: Instance of singleton class should be globally accessible so that each class can use it. In Java, it is done by making the access-specifier of instance public.

---

## Singleton class can be instantiated by 2 methods
- **Early initialization**: In this method, class is initialized whether it is to be used or not. The main advantage of this method is its simplicity. You initiate the class at the time of class loading. Its drawback is that class is always initialized whether it is being used or not.
- **Lazy initialization**: In this method, class in initialized only when it is required. It can save you from instantiating the class when you don’t need it. Generally, lazy initialization is used when we create a singleton class.

---

## Examples of Singleton class
1. **java.lang.Runtime**
2. **java.awt.Desktop**

java.lang.Runtime and java.awt.Desktop are 2 singleton classes provided by JVM.

---

## Applications of Singleton classes
There is a lot of applications of singleton pattern like cache-memory, database connection, drivers, logging.
1. Hardware interface access
2. Logger
3. Configuration File
4. Cache

---

## When to use Singleton pattern
- A class in your program should have just a single instance available to all clients
- You need stricter control over global variables

---

## Code Examples
**Safe Singleton**
A pure safe way to implement Singleton in Rust is using no global variables at all and passing everything around through function arguments. The oldest living variable is an object created at the start of the main().

safe.rs
```rust
fn change(global_state: &mut u32) {
   *global_state += 1;
}

fn main() {
   let mut global_state = 0u32;

   change(&mut global_state);

   println!("Final state: {}", global_state);
}
```

Starting with Rust 1.63, it can be easier to work with global mutable singletons, although it’s still preferable to avoid global variables in mostcases.

Now that Mutex::new is const, you can use global static Mutex locks without needing lazy initialization.
```rust
use std::sync::Mutex;

static ARRAY: Mutex<Vec<i32>> = Mutex::new(Vec::new());

fn do_a_call() {
    ARRAY.lock().unwrap().push(1);
}

fn main() {
    do_a_call();
    do_a_call();
    do_a_call();

    println!("Called {} times", ARRAY.lock().unwrap().len());
}
```

--- 

## References
- https://refactoring.guru/design-patterns/singleton/rust/example#example-2
- https://stackoverflow.com/questions/27791532/how-do-i-create-a-global-mutable-singleton