单例模式 Singleton

问题描述

代码示例

use lazy_static::lazy_static;
use std::sync::Mutex;

lazy_static! {
    pub static ref GLOBAL_PRESIDENT: Mutex<President> =
        Mutex::new(President::new("LazyStaticMacro"));
}

pub struct President {
    name: String,
}

impl President {
    #[must_use]
    pub const fn empty() -> Self {
        Self {
            name: String::new(),
        }
    }

    #[must_use]
    pub fn new(name: &str) -> Self {
        Self {
            name: name.to_owned(),
        }
    }

    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn set_name(&mut self, name: &str) {
        self.name.clear();
        self.name.push_str(name);
    }
}

fn main() {
    GLOBAL_PRESIDENT
        .lock()
        .unwrap()
        .set_name("Trump[lazy_static]");
    println!(
        "President name: {}",
        GLOBAL_PRESIDENT.lock().unwrap().name()
    );
}