Combining the state and observable patterns in Rust

147 views Asked by At

I've been interested in working with Rust for a while and wanted to recreate one of my school projects in it. This project involves creating an Order which goes through multiple stages much like this post from the rust docs.

However, a problem arose when trying to implement the observer pattern on the State of this Order. I want the ability to subscribe to this State and to do this the State should contain a Vector of Observers.

struct Order {
    order_state: Box<dyn State>,
}

impl Order {
    pub fn new() -> Order {
        return Order {
            order_state: Box::new(Created {}),
        };
    }

    pub fn print_state(&self) {
        self.order_state.print_state();
    }

    pub fn complete(&mut self) {
        self.order_state = Box::new(Completed {})
    }
}

trait State {
    fn print_state(&self);
}

struct Created {}

impl State for Created {
    /*
    This variable would specify a constraint on the state
    that the state must have a list of observers that have certain
    functionality.

    let observers: Vec<Observer>;

    fn send_update(&str) {
        observers.iter().foreach(|observer| observer.receiveMessage(&str))
    }
    */

    fn print_state(&self) {
        println!("I have been created!")
    }
}

struct Completed {}

impl State for Completed {
    fn print_state(&self) {
        println!("I have been completed!")
    }
}

fn main() {
    let mut a: Order = Order::new();
    a.print_state();

    a.complete();
    // a.send_update("Status changed!")
    a.print_state();
}

The thing is, traits cannot hold variables such as the Vec I was going to use. In C# (which I origionally build this in) we could overcome this by having an abstract class. My question now is, how do I combine these patterns in Rust?

I am aware that a proposal for variables in traits exists here but seeing as it was suggested back in 2016, I am not holding out hope.

0

There are 0 answers