用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);
   }	
相关推荐
DongLi018 小时前
rustlings 学习笔记 -- exercises/05_vecs
rust
番茄灭世神1 天前
Rust学习笔记第2篇
rust·编程语言
shimly1234561 天前
(done) 速通 rustlings(20) 错误处理1 --- 不涉及Traits
rust
shimly1234561 天前
(done) 速通 rustlings(19) Option
rust
@atweiwei1 天前
rust所有权机制详解
开发语言·数据结构·后端·rust·内存·所有权
shimly1234561 天前
(done) 速通 rustlings(24) 错误处理2 --- 涉及Traits
rust
shimly1234561 天前
(done) 速通 rustlings(23) 特性 Traits
rust
shimly1234561 天前
(done) 速通 rustlings(17) 哈希表
rust
shimly1234561 天前
(done) 速通 rustlings(15) 字符串
rust
shimly1234561 天前
(done) 速通 rustlings(22) 泛型
rust