单例是一种创建型设计模式， 让你能够保证一个类只有一个实例， 并提供一个访问该实例的全局节点。
单例拥有与全局变量相同的优缺点。 尽管它们非常有用， 但却会破坏代码的模块化特性。
在某些其他上下文中， 你不能使用依赖于单例的类。 你也将必须使用单例类。 绝大多数情况下， 该限制会在创建单元测试时出现。
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
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
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
unsafeblocks under the hood.
- See the thread about a mutable Singleton on Stackoverflow for more information.
Starting with Rust 1.63,
const, you can use global static
Mutex locks without needing lazy initialization. See the Singleton using Mutex example below.