This page looks best with JavaScript enabled

Singleton pattern

 ·  ☕ 1 min read  ·  ✍️ t1

The Singleton pattern is a software design pattern that ensures a class has only one instance, while providing a global access point to this instance. This is useful when we only need one instance of a class for the entire system, such as when we want to manage access to a shared resource.

To implement the Singleton pattern in Rust, we can use the lazy_static crate to create a global instance of the Singleton class that is initialized only when it is first used. Here is an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
extern crate lazy_static;

use std::sync::Mutex;

lazy_static! {
    static ref INSTANCE: Mutex<Singleton> = Mutex::new(Singleton {});
}

struct Singleton {
    // Some fields here...
}

impl Singleton {
    fn get_instance() -> MutexGuard<Singleton> {
        INSTANCE.lock().unwrap()
    }
}

In this example, the Singleton struct represents the class that we want to have only one instance of. The lazy_static! macro creates a global INSTANCE variable that holds a Mutex wrapping an instance of the Singleton struct. The get_instance method can be used to access the global Singleton instance, ensuring that only one thread can access it at a time using the Mutex synchronization mechanism.

Share on

t1
WRITTEN BY
t1
Dev