-
-
Save kyrylo/b0a989d5e23aa6afcd4bb6c5587d215a to your computer and use it in GitHub Desktop.
Filters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() { | |
let mut notifier = Notifier::new(); | |
notifier.add_filter(|n| n.incr_count(1)); | |
notifier.add_filter(|n| n.incr_count(1)); | |
let mut notice = Notice::new(); | |
println!("Before: {:#?}", notice); | |
notifier.notify(&mut notice); | |
println!("After: {:#?}", notice); | |
} | |
#[derive(Debug)] | |
struct Notice { | |
count: i32, | |
} | |
impl Notice { | |
pub fn new() -> Self { | |
Self { | |
count: 0, | |
} | |
} | |
pub fn incr_count(&mut self, count: i32) { | |
self.count += count; | |
} | |
} | |
struct Notifier<'a> { | |
filters: Vec<Box<Fn(&mut Notice) + 'a>> | |
} | |
impl<'a> Notifier<'a> { | |
pub fn new() -> Self { | |
Self { | |
filters: Vec::new(), | |
} | |
} | |
pub fn add_filter<T: Fn(&mut Notice) + 'a>(&mut self, filter: T) { | |
self.filters.push(Box::new(filter)); | |
} | |
pub fn notify(&self, notice: &mut Notice) { | |
for filter in &self.filters { | |
filter(notice); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment