用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);
   }	
相关推荐
柯南46688 小时前
【AI开发之Rust】第 8 课:泛型、trait 与 trait 对象
rust·编程语言
yume_sibai9 小时前
12-Rust 性能优化指南(性能分析 + 内存优化 + SIMD + 并发优化 + 编译器优化 + 基准测试)
开发语言·性能优化·rust
geovindu9 小时前
rust:Builder Pattern
开发语言·设计模式·rust·建造者模式
传奇开心果编程13 小时前
【Rust入门知识点学与练】第33课:异步编程入门(async/await)强化
开发语言·学习·rust
传奇开心果编程13 小时前
【Rust入门知识点学与练】第34课:所有权与借用
开发语言·学习·rust
柒儿吖14 小时前
SSCom 重构全记录:用 Rust 把串口调试助手送上鸿蒙 PC、macOS、Windows和Linux
测试工具·rust·harmonyos
Kapaseker15 小时前
Rust 为什么越来越受欢迎?开发者角度谈
rust
孙启超16 小时前
【AI开发之Rust】第 6 课:结构体、枚举与方法 —— 开始定义自己的类型
开发语言·人工智能·后端·ai·rust
foolishlee16 小时前
Rust 下载依赖包
rust
蓝宝石的傻话16 小时前
MiBee Eye 蜂眼:把闲置的 Linux 小板做成一台能进国标平台的摄像头
golang·rust