用Rust实现23种设计模式之单例

话不多说,上代码!

1. 使用Arc + Mutex

在这个例子中,我们使用了 Arc (原子引用计数)和 Mutex (互斥锁)来实现线程安全的单例。通过 get_instance 方法,我们可以获取到单例实例,并对实例进行操作。

bash 复制代码
use std::sync::{Arc, Mutex};
 struct Singleton {
    // 单例数据
    data: String,
}
 impl Singleton {
    // 获取单例实例的方法
    fn get_instance() -> Arc<Mutex<Singleton>> {
        // 使用懒加载创建单例实例
        // 这里使用了 Arc 和 Mutex 来实现线程安全的单例
        // 只有第一次调用 get_instance 时会创建实例,之后都会返回已创建的实例
        static mut INSTANCE: Option<Arc<Mutex<Singleton>>> = None;
         unsafe {
            INSTANCE.get_or_insert_with(|| {
                Arc::new(Mutex::new(Singleton {
                    data: String::from("Singleton instance"),
                }))
            }).clone()
        }
    }
}
 fn main() {
    // 获取单例实例
    let instance1 = Singleton::get_instance();
    let instance2 = Singleton::get_instance();
     // 修改单例数据
    {
        let mut instance = instance1.lock().unwrap();
        instance.data = String::from("Modified singleton instance");
    }
     // 输出单例数据
    {
        let instance = instance2.lock().unwrap();
        println!("{}", instance.data);
    }
}

2. 使用lazy_static的懒加载

使用 lazy_static crate: lazy_static crate 是一个常用的 Rust crate,可以实现懒加载的全局静态变量。通过 lazy_static ,可以在需要时创建单例实例,并确保只有一个实例被创建

bash 复制代码
use lazy_static::lazy_static;
   use std::sync::Mutex;
    struct Singleton {
       // 单例数据
       data: String,
   }
    lazy_static! {
       static ref INSTANCE: Mutex<Singleton> = Mutex::new(Singleton {
           data: String::from("Singleton instance"),
       });
   }
    fn main() {
       // 获取单例实例
       let instance = INSTANCE.lock().unwrap();
       println!("{}", instance.data);
   }

3. 使用once_cell crate

使用 once_cell crate: once_cell crate 是另一个常用的 Rust crate,可以实现懒加载的全局静态变量。通过 once_cell ,可以在首次访问时创建单例实例,并确保只有一个实例被创建

bash 复制代码
use once_cell::sync::Lazy;
    struct Singleton {
       // 单例数据
       data: String,
   }
    static INSTANCE: Lazy<Singleton> = Lazy::new(|| Singleton {
       data: String::from("Singleton instance"),
   });
    fn main() {
       // 获取单例实例
       let instance = INSTANCE.clone();
       println!("{}", instance.data);
   }

4. 使用 Rc 和 RefCell

使用 Rc 和 RefCell : Rc 是 Rust 标准库中的引用计数类型, RefCell 是一个提供内部可变性的类型。结合使用 Rc 和 RefCell ,可以实现简单的单例模式。示例代码如下:

bash 复制代码
use std::rc::Rc;
   use std::cell::RefCell;
    struct Singleton {
       // 单例数据
       data: String,
   }
    fn main() {
       // 创建单例实例
       let instance = Rc::new(RefCell::new(Singleton {
           data: String::from("Singleton instance"),
       }));
        // 获取单例实例
       let borrowed_instance = instance.borrow();
       println!("{}", borrowed_instance.data);
   }	
相关推荐
xuejianxinokok7 小时前
什么是代数类型 ? java为什么要添加record,Sealed class 和增强switch ?
后端·rust
Kiri霧9 小时前
在actix-web中创建一个提取器
后端·rust·web
^_^ 纵歌9 小时前
rust主要用于哪些领域
开发语言·后端·rust
l1t21 小时前
测试DuckDB电子表格读取插件rusty_sheet 0.2版
数据库·rust·插件·xlsx·duckdb
嚴寒1 天前
被10个终端窗口逼疯后,我用Rust写了个零依赖跨平台终端Agent启动神器
rust·agent
林开落L2 天前
线程进阶:线程池、单例模式与线程安全深度解析
linux·安全·单例模式·线程池
岁岁岁平安2 天前
Java的双重检查锁机制(DCL)与懒加载的单例模式
java·单例模式·synchronized·
alwaysrun2 天前
Rust中模式匹配
rust·match·模式匹配·if let·while let·值绑定
编码浪子3 天前
Dioxus hot-dog 总结
rust
光影少年3 天前
rust生态及学习路线,应用领域
开发语言·学习·rust