DBA学RUST设计模式--观察者模式

时间:2021-07-01 16:45:32   收藏:0   阅读:0
#[derive(Debug, Clone)]
struct Work { //消息实体,存储消息
    id: i32
}

struct WorkMaster {  //消息管理者属性
    workers: Vec<Box<Worker>> //存储注册的接收者。每个接收者须实现Worker接口才能注册进。  
}

impl WorkMaster {
    fn register_worker(&mut self, worker: Box<Worker>) { //注册接收者
        self.workers.push(worker);
    }
    fn dispatch_new_work(&self, work: Work) {//为接收者队列中的每个成员发送通知 
        for worker in &self.workers {
            worker.on_new_work(work.clone())//由于每个接收者都实现了Worker接口,此处可方便的调用实例化的接收者方法
        }
    }
}

trait Worker {
    fn on_new_work(&self, work: Work);//self:消息接收者(列表) work:消息实体
}
//通过构建不同的接收者,将消息发送与接收分离。
//接收者为彼此独立的结构体,而发送者维护一个存储了接收者的vec列表
//也可理解为,当WorkMaster状态发生改变时,所有依赖于他的对象都会接收到通知
struct LocalWorker {} impl Worker for LocalWorker { fn on_new_work(&self, work: Work) { println!("local worker receiver new work {:?}", work) } } struct RemoteWorker {} impl Worker for RemoteWorker { fn on_new_work(&self, work: Work) { println!("remote worker receive new work {:?}", work) } }

 

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn observer_mode_test() {
        let mut master = WorkMaster{workers: Vec::new()};
        let local_worker = LocalWorker{};
        let remote_worker = RemoteWorker{};
        master.register_worker(Box::new(local_worker));
        master.register_worker(Box::new(remote_worker));
        // local worker receiver new work Work { id: 1 }
        // remote worker receive new work Work { id: 1 }
        master.dispatch_new_work(Work{id: 1});
    }
}

  

 WorkMaster通过关联函数dispatch_new_work,通知接收者自己状态发生了改变。

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!