How can I implement the observer pattern in Rust?

后端 未结 5 985
轻奢々
轻奢々 2020-12-28 17:01

I have an observable collection and an observer. I want the observer to be a trait implementation of trait Observer. The observable object should be able to not

5条回答
  •  难免孤独
    2020-12-28 17:45

    I used a callback function. It's simple and powerful and there are no lifetime issues or type erasure.

    I tried Weak, but

    1. It needs an Rc
    2. You have to repeat code to create a different observer struct.
    3. It requires type erasure
    pub struct Notifier {
        subscribers: Vec>,
    }
    
    impl Notifier {
        pub fn new() -> Notifier {
            Notifier {
                subscribers: Vec::new(),
            }
        }
    
        pub fn register(&mut self, callback: F)
        where
            F: 'static + Fn(&E),
        {
            self.subscribers.push(Box::new(callback));
        }
    
        pub fn notify(&self, event: E) {
            for callback in &self.subscribers {
                callback(&event);
            }
        }
    }
    

提交回复
热议问题