use std::collections::HashMap;
pub struct Message {
pub kind: String,
pub json: String,
}
pub trait MessageHandler {
fn handle(&self, msg: &Message);
}
pub struct Mediator {
storage: HashMap<String, &'static dyn MessageHandler>,
}
impl Mediator {
pub fn new() -> Self {
Self {
storage: HashMap::with_capacity(100),
}
}
pub fn add(&mut self, kind: String, handler: &'static dyn MessageHandler) {
self.storage.insert(kind, handler);
}
pub fn invoke(&self, msg: &Message) {
let kind = msg.kind.clone();
if self.storage.contains_key(&kind) {
let handler = self.storage.get(&kind).unwrap();
handler.handle(msg);
}
}
}
use std::collections::HashMap;
pub struct Message {
pub kind: String,
pub json: String,
}
pub trait MessageHandler {
fn handle(&self, msg: &Message);
}
pub struct Mediator {
storage: HashMap<String, Vec<&'static dyn MessageHandler>>,
}
impl Mediator {
pub fn new() -> Self {
Self {
storage: HashMap::with_capacity(100),
}
}
pub fn add(&mut self, kind: String, handler: &'static dyn MessageHandler) {
let key = kind.clone();
if self.storage.contains_key(&key) {
let handlers = self.storage.get_mut(&key).unwrap();
handlers.push(handler);
} else {
let mut handlers: Vec<&'static dyn MessageHandler> = Vec::new();
handlers.push(handler);
self.storage.insert(key, handlers);
}
}
pub fn invoke(&self, msg: &Message) {
let kind = msg.kind.clone();
if self.storage.contains_key(&kind) {
let handlers = self.storage.get(&kind).unwrap();
for handler in handlers {
handler.handle(msg);
}
}
}
}