SOLDES de printemps
Singleton

Singleton en Rust

Le Singleton est un patron de conception de création qui s’assure de l’existence d’un seul objet de son genre et fournit un unique point d’accès vers cet objet.

Le singleton possède à peu près les mêmes avantages et inconvénients que les variables globales. Même s’ils sont super utiles, ils réduisent la modularité du code.

Vous ne pourrez pas utiliser une classe qui dépend d’un singleton dans un autre contexte. Vous devrez également inclure complètement la classe Singleton dans votre code. En général, on se rend compte de cette limitation lorsque l’on crée des tests unitaires.

Rust specifics

By definition, Singleton is a global mutable object. In Rust this is a static mut item. Thus, to avoid all sorts of concurrency issues, the function or block that is either reading or writing to a mutable static variable should be marked as an unsafe block.

For this reason, the Singleton pattern can be percieved as unsafe. However, the pattern is still widely used in practice. A good read-world example of Singleton is a log crate that introduces log!, debug! and other logging macros, which you can use throughout your code after setting up a concrete logger instance, such as env_logger. As we can see, env_logger uses log::set_boxed_logger under the hood, which has an unsafe block to set up a global logger object.

  • In order to provide safe and usable access to a singleton object, introduce an API hiding unsafe blocks under the hood.
  • See the thread about a mutable Singleton on Stackoverflow for more information.

Starting with Rust 1.63, Mutex::new is const, you can use global static Mutex locks without needing lazy initialization. See the Singleton using Mutex example below.

Singleton dans les autres langues

Singleton en C# Singleton en C++ Singleton en Go Singleton en Java Singleton en PHP Singleton en Python Singleton en Ruby Singleton en Swift Singleton en TypeScript