rust初体验之观察者模式

项目环境

1.idea 2019.1.3
2.rust 1.20.2 (13979c968 2019-10-16)

实现思路

抽象观察者
trait Observer {
    fn update(&self, msg: &str);
}
抽象被观察者接口
trait Observerable {
   fn register_observer(&mut self, obj: Box);
   fn remove_observer(&mut self, index: usize);
   fn notify_observer(&self);
}
主要实现:
struct WechatServer {
    msg: &'static str,
    list: Vec>
}

impl WechatServer {
    fn new() -> WechatServer{
        return WechatServer{
            list: Vec::new(),
            msg: ""
        };
    }

	// 发送消息通知
    fn set_data_msg(&mut self, msg: &'static str) {
        self.msg = msg;
        self.notify_observer();
    }
}

impl Observerable for WechatServer {
    fn register_observer(&mut self, obj: Box) {
        self.list.push(obj)
    }
    
	fn remove_observer(&mut self, index: usize) {
        self.list.remove(index);
    }
    
    fn notify_observer(&self) {
        for obj in self.list.iter() {
            obj.update(self.msg);
        }
    }
}
struct User {
    name: &'static str
}

impl Observer for User{
    fn update(&self, msg: &str) {
        println!("{} -> 收到消息: {}", self.name, msg);
    }
}
调用
fn main() {
    let mut server = WechatServer::new();
    
    server.register_observer(Box::new(User{name:"张三"}));
    server.register_observer(Box::new(User{name:"李四"}));
    server.register_observer(Box::new(User{name:"王五"}));

    server.set_data_msg("这是测试消息");
    server.register_observer(Box::new(User{name:"赵六"}));
    server.remove_observer(1);
    server.register_observer(Box::new(User{name:"田七"}));
    server.set_data_msg("rust是最棒的");
}

总结

通过dyn标记数据类型是trait ,达到其它语言中接口做参数或返回值的效果

你可能感兴趣的:(rust,rust)