struct Message<T> {
kind: String,
payload: T,
}
trait MessageHandler<T> {
fn can_handle_message_kinds(&self) -> [String];
fn handle(&self, msg: &Message<T>);
}
trait Mediator {
fn register<T>(handler: dyn MessageHandler<T>);
fn signal<T>(msg: &Message<T>);
}
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);
}
}
}