Introduction

Welcome back to our course on "Applying Design Patterns to Real-World Problems in Rust"! 🎉 In this second lesson, we're diving into two more essential design patterns: Observer and Strategy. These patterns will help us tackle common challenges in smart home systems, enhancing our ability to create a responsive security setup and a flexible climate control system. Let's explore how Rust empowers us to implement these patterns efficiently and elegantly!

Observer Pattern for Smart Home Security System

In a smart home security system, it's common to have multiple types of sensors that need to respond to certain events, like an alarm trigger. As new sensor types are developed or installed, we want to be able to integrate them without modifying the core security system code. The Observer pattern facilitates this by decoupling the security system from the sensors, allowing for the dynamic addition and removal of observers.

Define Alarm Listener Trait and Security Control Struct

We'll begin by defining an AlarmListener trait, which serves as a contract for any sensor that wants to listen for alarm events. Then, we'll create the SecurityControl struct, which manages the list of listeners and notifies them when the alarm is triggered.

Rust
// Define the AlarmListener trait
pub trait AlarmListener {
    fn alarm(&self);
}

// Define the SecurityControl struct
pub struct SecurityControl {
    listeners: Vec<Box<dyn AlarmListener>>,
}

impl SecurityControl {
    pub fn new() -> Self {
        SecurityControl {
            listeners: Vec::new(),
        }
    }

    pub fn add_listener(&mut self, listener: Box<dyn AlarmListener>) {
        self.listeners.push(listener);
    }

    pub fn trigger_alarm(&self) {
        for listener in &self.listeners {
            listener.alarm();
        }
    }
}

In this code:

  • AlarmListener Trait: Defines the alarm method, which will be implemented by all sensors.
  • SecurityControl Struct: Manages a list of listeners, each implementing the AlarmListener trait, with the add_listener method that adds a new listener to the system and the trigger_alarm method that notifies all registered listeners by calling their alarm method.
Create Sensor Structs Implementing AlarmListener
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal