Advertisement
Xiphoseer

Event Dispatch

Oct 10th, 2019
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 0.79 KB | None | 0 0
  1. use std::collections::HashMap;
  2. use std::hash::Hash;
  3.  
  4. trait Listener<T,C> {
  5.     fn handle(&mut self, evt: T, ctx: &mut C);
  6. }
  7.  
  8. struct Dispatcher<T,C> where T: Hash + Eq {
  9.     events: HashMap<T, Vec<Box<dyn Listener<T,C>>>>,
  10. }
  11.  
  12. impl<T,C> Default for Dispatcher<T,C> where T: Hash + Eq {
  13.     fn default() -> Self {
  14.         Self{events: HashMap::default()}
  15.     }
  16. }
  17.  
  18. impl<T,C> Dispatcher<T,C> where T: Hash + Eq {
  19.     fn dispatch(&mut self, _event: T, context: &mut C) {
  20.  
  21.     }
  22. }
  23.  
  24. #[derive(Hash, PartialEq, Eq)]
  25. enum Event {
  26.     A,B,C,
  27. }
  28.  
  29. struct Context {
  30.     some: bool,
  31. }
  32.  
  33. fn main() {
  34.     let mut dispatcher = Dispatcher::default();
  35.  
  36.     let mut ctx = Context{some: true};
  37.  
  38.     let event = Event::A;
  39.     dispatcher.dispatch(event, &mut ctx);
  40.  
  41.     let event = Event::B;
  42.     dispatcher.dispatch(event, &mut ctx);
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement