Observer Pattern

The Observer pattern is a behavioral design pattern where an object (the subject) maintains a list of its dependents (observers) and notifies them of any state changes, usually by calling one of their methods.

Step-by-Step Plan

1- Define the Observer trait: Create a trait that observers must implement.
2- Define the Subject struct: Create a struct that maintains a list of observers and notifies them of changes.
3- Implement the Observer trait for concrete observers: Create concrete observer structs that implement the Observer trait.
4- Main function: Create a subject, add observers, and notify them of changes.

// Observer type
pub trait Observer {
    fn update(&self, message: &str);
}

// Concrete observer
pub struct ConcreteObserver {
    name: String,
}

impl ConcreteObserver {
    pub fn new(name: &str) -> Self {
        ConcreteObserver {
            name: name.to_string(),
        }
    }
}

impl Observer for ConcreteObserver {
    fn update(&self, message: &str) {
        println!("{} received message: {}", self.name, message);
    }
}

// Subject
pub struct Subject {
    observers: Vec<Box<dyn Observer>>,
}

impl Subject {
    pub fn new() -> Self {
        Subject {
            observers: Vec::new(),
        }
    }

    pub fn add_observer(&mut self, observer: Box<dyn Observer>) {
        self.observers.push(observer);
    }

    pub fn notify_observers(&self, message: &str) {
        for observer in &self.observers {
            observer.update(message);
        }
    }
}

fn main() {
    let mut subject = Subject::new();

    let observer1 = ConcreteObserver::new("Observer 1");
    let observer2 = ConcreteObserver::new("Observer 2");

    subject.add_observer(Box::new(observer1));
    subject.add_observer(Box::new(observer2));

    subject.notify_observers("Hello, observers!");
}

In this example:

  • Observer Trait: Defines the update method that observers must implement.
  • Subject Struct: Manages a list of observers and notifies them of changes.
  • Concrete Observers: Implement the Observer trait and define the update method.
  • Main Function: Demonstrates the pattern by creating a subject, adding observers, and notifying them.

This setup allows the subject to notify all registered observers whenever a change occurs, following the Observer pattern principles.