Skip to content

Commit

Permalink
singleton
Browse files Browse the repository at this point in the history
  • Loading branch information
lpxxn committed Feb 26, 2020
1 parent 2f908b0 commit a415abb
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 2 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
| [Factory Method](/creational/factory.rs) | Defers instantiation of an object to a specialized function for creating instances ||
| [Abstract Factory](/creational/abstract_factory.rs) | Provides an interface for creating families of releated objects ||
| [Builder](/creational/builder.rs) | Builds a complex object using simple objects ||
| [Singleton](/creational/singleton.rs) | Restricts instantiation of a type to one object ||



Expand Down
3 changes: 1 addition & 2 deletions creational/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ impl Product {
for v in &self.parts {
println!("{}", v);
}

println!("{0}{1}{0}", "*".repeat(10), "*".repeat(parts_list.len()));
}
}
Expand Down Expand Up @@ -128,7 +127,7 @@ fn main() {
direct.construct();
let product = direct.builder.get_product();
product.list_parts();
// output:
// output:
/*
********** parts **********
part a1
Expand Down
35 changes: 35 additions & 0 deletions creational/singleton.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
use std::sync::{Arc, Mutex};

#[derive(Debug)]
struct Config {
db_connection_str: String,
}

fn get_config() -> Arc<Mutex<Config>> {
static mut CONF: Option<Arc<Mutex<Config>>> = None;
unsafe {
CONF.get_or_insert_with(|| {
println!("init"); // do once
Arc::new(Mutex::new(Config {
db_connection_str: "abcdef".to_string(),
}))
})
.clone()
}
}

fn main() {
let f1 = get_config();
println!("{:?}", f1);
// modify
{
let mut conf = f1.lock().unwrap();
conf.db_connection_str = "hello".to_string();
}

let f2 = get_config();
println!("{:?}", f2);
let conf2 = f2.lock().unwrap();

assert_eq!(conf2.db_connection_str, "hello".to_string())
}

0 comments on commit a415abb

Please sign in to comment.