Behavioral Patterns 2: Keeping Track
local graph
Chapter 8 — Behavioral Patterns 2: Keeping Track
Section titled “Chapter 8 — Behavioral Patterns 2: Keeping Track”Behavioral Patterns 2: Keeping Track
Section titled “Behavioral Patterns 2: Keeping Track”In this chapter, we’ll explore the second set of behavioral design patterns in Rust and see how they can enhance our calculator with better state management, data traversal, and optimization capabilities. These patterns help us manage the flow of information and control within our application, making it more robust, maintainable, and responsive to changes.
We’ll continue developing our Correct Calculator project, building on the patterns established in previous chapters. By now, our calculator has a solid foundation built with creational patterns, a well-organized structure courtesy of structural patterns, and the ability to process operations thanks to the behavioral patterns from the previous chapter. The patterns in this chapter will complete our calculator, transforming it into a full-featured application that can handle complex scenarios elegantly.
These design patterns have their origins in traditional object-oriented programming languages, so they are built around thinking in terms of “objects.” Because Rust doesn’t have traditional objects, we will reinvent the implementation of these patterns to use more natural features of the language. However, as we discuss the patterns, we will speak of “objects” as a mental model.
First, we’ll examine the Iterator pattern, a core feature of Rust that provides a consistent way to traverse collections. This will help us work with calculation history, expression trees, and other collections in our calculator. Then, we’ll explore the State pattern, which allows an object to alter its behavior when its internal state changes – perfect for implementing different calculator modes with different available operations.
Next, we’ll look at the Memento pattern, which lets us save and restore an object’s state, enabling features like calculation snapshots and session persistence. We’ll also study the Observer pattern, which establishes a communication mechanism between objects, allowing our calculator to react to changes in variables or settings. Finally, we’ll examine the Visitor pattern, which enables operations across an object structure without modifying its implementation, ideal for tasks like expression optimization and validation.
Throughout the chapter, we’ll see how these patterns can be implemented in Rust, taking advantage of the language’s powerful type system, ownership model, and trait-based polymorphism. We’ll also see how these patterns can work together with those from previous chapters to create a cohesive, well-designed application.
In this chapter we’re going to cover the following main topics:
- Iterator pattern: efficient collection traversal
- State pattern: changing behavior based on state
- Memento pattern: capturing and restoring state
- Observer pattern: reacting to changes
- Visitor pattern: separating algorithms from objects
Iterator pattern: efficient collection traversal
Section titled “Iterator pattern: efficient collection traversal”The Iterator pattern provides a way to access elements of a collection sequentially without exposing the underlying representation. Unlike in many other languages where iterators are implemented as separate design patterns, in Rust they’re a core feature of the language, deeply integrated into the standard library and language syntax. This tight integration makes iterators both powerful and efficient.
In Rust, the Iterator pattern is formalized through the Iterator trait:
pub trait Iterator { type Item; fn next(&mut self) -> Option<Self::Item>; // Many default methods provided...}This trait has a single required method, next(), which returns the next element of the collection, or None if there are no more elements. The trait also provides many default methods, such as map (which transforms each element), filter (which selects elements matching a predicate), fold (which accumulates elements into a single value), and collect (which gathers elements into a collection like Vec or HashMap). Dozens more combinators are available; see the Iterator documentation in the standard library (https://doc.rust-lang.org/std/iter/trait.Iterator.html) for the complete list. These build on next() to create powerful transformations.
What makes Rust’s iterators particularly powerful is that they’re zero-cost abstractions. They compile down to efficient machine code with no runtime overhead compared to manual iteration. Iterators are also lazy: calling filter() or map() does not process any elements immediately. Instead, it creates a new iterator that will apply the transformation when elements are eventually consumed by a terminal operation such as collect() or sum(). This means chaining multiple transformations is cheap; no intermediate collections are created. When you chain iterator methods like filter().map().collect(), the compiler optimizes this into a single efficient loop. Rust also provides special syntax for working with iterators: for loops are syntactic sugar for iterator consumption.
The need for collection iteration
Section titled “The need for collection iteration”Our calculator works with various collections: expressions, variables, calculation history, and more. We need consistent and efficient ways to traverse these collections without exposing their implementation details. For example, we might want to navigate through calculation history to find previous results, traverse expression trees for analysis or optimization, examine variables to find dependencies, or process commands in sequence.
Without a proper abstraction for iteration, we would need indexing or custom traversal logic for each collection type, leading to inconsistent, error-prone code. The Iterator pattern provides a uniform interface that works across all these scenarios.
We’ll implement custom iterators in three stages: a basic history iterator for sequential access, a tree iterator for hierarchical expression traversal, and a double-ended iterator for bidirectional navigation.
Implementing a history iterator
Section titled “Implementing a history iterator”Let’s start with a simple iterator for our calculator’s history. Users often want to review past calculations, search for specific expressions, or extract recent results:
struct HistoryIterator<'a> { history: &'a [Calculation], position: usize,}
impl<'a> HistoryIterator<'a> { fn new(history: &'a [Calculation]) -> Self { Self { history, position: 0 } }}The iterator holds a reference to a slice of Calculation structs and tracks the current position within that slice. The lifetime 'a ensures the iterator cannot outlive the history it references. Rust’s borrow checker enforces this at compile time: if you tried to delete or modify the history while an iterator still exists, the compiler rejects the code with a borrow error. The iterator holds an immutable reference to the history slice, which prevents any mutation of the underlying data until the iterator is dropped. This compile-time guarantee eliminates an entire class of bugs that plague iterator implementations in other languages.
The iterator implementation advances through the slice, returning each calculation in sequence:
impl<'a> Iterator for HistoryIterator<'a> { type Item = &'a Calculation;
fn next(&mut self) -> Option<Self::Item> { if self.position < self.history.len() { let item = &self.history[self.position]; self.position += 1; Some(item) } else { None } }}The next method returns a reference to the current calculation and advances the position. When we’ve traversed all elements, it returns None. This simple implementation unlocks all of Rust’s iterator combinators.
We can use this iterator to implement powerful search and filtering operations:
impl Calculator { fn history_iter(&self) -> HistoryIterator { HistoryIterator::new(&self.history) }
fn search_history(&self, pattern: &str) -> Vec<&Calculation> { self.history_iter() .filter(|calc| calc.expression.contains(pattern)) .collect() }
fn recent_results(&self, count: usize) -> Vec<f64> { self.history_iter() .rev() .take(count) .map(|calc| calc.result) .collect() }}Notice how we chain iterator combinators like filter, rev (we’ll implement DoubleEndedIterator shortly, which enables this .rev() call), take, and map to create complex operations with clean, readable code. The recent_results method reverses the iterator, takes the first count items (which are actually the most recent), and extracts just the result values.
Traversing expression trees
Section titled “Traversing expression trees”Our calculator uses expression trees built with the Composite pattern from Chapter 6, Structural Patterns: Connecting and Aggregating Components. Traversing these hierarchical structures requires a more sophisticated iterator that can handle nested nodes:
struct ExpressionIterator<'a> { stack: Vec<&'a dyn Expression>,}
impl<'a> ExpressionIterator<'a> { fn new(root: &'a dyn Expression) -> Self { let mut stack = Vec::new(); stack.push(root); Self { stack } }}The lifetime 'a ties the iterator to the expression tree it traverses: the iterator borrows references to expression nodes, so it cannot outlive the tree itself. This iterator uses a stack to implement depth-first traversal. The stack starts with the root expression, and as we visit each node, we push its children onto the stack for later processing, as shown in Figure 8.1.
Figure 8.1: The Expression tree for 3 * (x + 2)
[figure outside: Figure 8.1]
To make the iterator work, we implement the Iterator trait:
impl<'a> Iterator for ExpressionIterator<'a> { type Item = &'a dyn Expression;
fn next(&mut self) -> Option<Self::Item> { if let Some(node) = self.stack.pop() { // Push children onto stack for depth-first traversal // as_binary_op() is a downcast method on Expression that // returns Some(&BinaryOperation) if the expression is a // binary operation, or None otherwise. as_function() works // similarly for FunctionCall.
if let Some(op) = node.as_binary_op() { self.stack.push(&*op.right); self.stack.push(&*op.left); } else if let Some(func) = node.as_function() { self.stack.push(&*func.argument); } Some(node) } else { None } }}The &*op.right syntax deserves explanation: op.right is a Box, so *op.right dereferences the Box to get the dyn Expression value, and & borrows it to create a &dyn Expression reference suitable for our stack. This dereference-then-borrow pattern is common when working with Box in Rust.
Depth-first traversal visits each node before its children get processed (pre-order traversal), which is useful for operations like printing the expression or calculating the expression’s complexity. The order of pushing children matters. We push right to left so that left gets processed first (since we pop from the end).
Figure 8.2: Depth-first traversal of the expression 3 * (x + 2), showing the ExpressionIterator stack state at each step
We can use this iterator for expression analysis:
fn find_constant_nodes<'a>(expr: &'a dyn Expression) -> Vec<&'a dyn Expression> { expr.iter() .filter(|node| node.is_constant()) .collect()}
fn count_operations(expr: &dyn Expression) -> usize { expr.iter() .filter(|node| node.is_operation()) .count()}These methods demonstrate how iterators enable declarative code that clearly expresses intent. Rather than writing recursive traversal logic, we describe what we want – constant nodes or operation counts – and the iterator handles the traversal details.
Note that we need to add an iter() method and an is_operation() method to Expression that returns an ExpressionIterator (as shown in the code repository).
Implementing double-ended iterators
Section titled “Implementing double-ended iterators”Sometimes we need to iterate through a collection from either end. Rust provides the DoubleEndedIterator trait for this. To support it, we extend our iterator to track both ends of the collection:
struct HistoryIterator<'a> { history: &'a [Calculation], front: usize, back: usize,}
impl<'a> HistoryIterator<'a> { fn new(history: &'a [Calculation]) -> Self { Self { history, front: 0, back: history.len(), } }}The enhanced iterator maintains two indices: front for forward iteration and back for reverse iteration. They converge toward each other as iteration proceeds.
The forward Iterator implementation checks whether front has reached back before returning the next element. The DoubleEndedIterator works from the opposite end, decrementing back:
impl<'a> Iterator for HistoryIterator<'a> { type Item = &'a Calculation;
fn next(&mut self) -> Option<Self::Item> { if self.front < self.back { let item = &self.history[self.front]; self.front += 1; Some(item) } else { None } }}
impl<'a> DoubleEndedIterator for HistoryIterator<'a> { fn next_back(&mut self) -> Option<Self::Item> { if self.front < self.back { self.back -= 1; Some(&self.history[self.back]) } else { None } }}The next_back method works from the end, decrementing the back index and returning the element at that position, while next() advances from the front. When front and back meet, iteration is complete from both directions. This enables the rev() method and efficient operations on the most recent elements.
[figure outside: Figure 8.3]
Figure 8.3: Double-ended iterator showing bidirectional history navigation
Integration with the calculator interface
Section titled “Integration with the calculator interface”Let’s integrate these iterators into our calculator’s user interface. The history command collects all calculations and formats them for display:
fn process_command(&mut self, command: &str) -> Result<String, String> { match command.split_whitespace().next().unwrap_or("") { "history" => { let history: Vec<_> = self.calculator.history_iter().collect(); if history.is_empty() { Ok("No calculation history".to_string()) } else { let mut result = String::from("Calculation history:\n"); for (i, calc) in history.iter().enumerate() { result.push_str(&format!( " {}. {} = {}\n", i + 1, calc.expression, calc.result )); } Ok(result) } } // ... _ => Err("Unknown command".to_string()) }}The Vec<_> type annotation on history is not optional. Rust’s collect() method is generic over its return type: it can produce a Vec, a HashSet, a BTreeMap, a String, or any other type that implements FromIterator. The compiler cannot decide which collection you want from the context alone, so you must specify at least the container type. The underscore in Vec<_> tells the compiler “I want a Vec, but you can figure out the element type yourself.” The element type (&Calculation) is known from the iterator’s Item type, so there is no ambiguity once we have told the compiler we want a Vec. The history command collects all calculations into a vector and formats them with numbered entries. Collecting first, rather than formatting during iteration, keeps the borrowing straightforward since we don’t hold a mutable borrow on the calculator while building the output string.
The search command leverages our search_history method, which uses the iterator internally:
"search" => { let parts: Vec<&str> = command.split_whitespace().collect(); if parts.len() < 2 { return Err("Missing search pattern".to_string()); } let pattern = parts[1]; let matches = self.calculator.search_history(pattern);
// Format and return results... let mut result = String::from("Search results:\n"); for (i, calc) in matches.iter().enumerate() { result.push_str(&format!( " {}. {} = {}\n", i + 1, calc.expression, calc.result )); } Ok(result) }Users can search their calculation history with simple commands, all powered by our iterator infrastructure.
When to use custom iterators
Section titled “When to use custom iterators”As we mentioned earlier, Rust’s iterator system is uniquely powerful because it’s a zero-cost abstraction. Iterators are also lazy, meaning they don’t process elements until consumed. For example, a take(5) chain stops after finding five matching items rather than processing the entire collection.
Types implementing IntoIterator integrate directly with for loops. The IntoIterator trait has a single method, into_iter(), which converts a type into an iterator. When you write a for loop, Rust automatically calls into_iter() on the value. Standard collections like Vec already implement IntoIterator, which is why we can write this:
for calc in &calculator.history { println!("{} = {}", calc.expression, calc.result);}Given these built-in capabilities, custom iterators are appropriate when your data structures go beyond standard collections. Our expression tree iterator handles hierarchical traversal that Vec or HashMap iterators can’t express. Custom iterators also make sense when you want to hide implementation details. Callers of history_iter() don’t need to know whether history is stored in a Vec, a ring buffer, or a database.
In our calculator, iterators provide efficient traversal of calculation history, expression trees, and variable collections. They enable features like history search, expression optimization, and variable dependency tracking through clean, composable chains that clearly express intent.
In the next section, we’ll explore the State pattern, which allows our calculator to change its behavior based on its current mode.
State pattern: changing behavior based on state
Section titled “State pattern: changing behavior based on state”The traditional State pattern allows an object to alter its behavior when its internal state changes, appearing to change its “class” at runtime. By encapsulating state-specific behaviors into separate objects and delegating execution to the current state, we eliminate complex conditional logic and make state transitions explicit and manageable. Rust does not have classes, but the State pattern lets us evolve the behavior of a type.
The need for modal behavior
Section titled “The need for modal behavior”As our calculator matures, it needs to behave differently in different contexts. In standard mode, it performs basic arithmetic operations. In scientific mode, it handles trigonometric functions, logarithms, and higher mathematics. In programmer mode, it deals with binary, octal, and hexadecimal numbers, plus bitwise operations. (We will implement Standard and Scientific modes in this chapter; Programmer mode follows the same pattern and its implementation is left as an exercise in the code repository.)
Each mode has different supported operations, input handling, and output formatting. Without a proper pattern, we end up with conditionals scattered throughout our code:
impl Calculator { fn process_input(&mut self, input: &str) -> Result<f64, String> { match self.mode { CalculatorMode::Standard => { // Standard mode logic... todo!() } CalculatorMode::Scientific => { // Scientific mode logic... todo!() } CalculatorMode::Programmer => { // Programmer mode logic... todo!() } } }
fn display_result(&self, value: f64) -> String { match self.mode { CalculatorMode::Standard => format!("{}", value), CalculatorMode::Scientific => format!("{:e}", value), CalculatorMode::Programmer => format!("0x{:X}", value as u64), } }
// Many more methods with similar conditional logic...}To solve this, we can define the InputResult enum to handle the result of input processing, including mode changes:
pub enum InputResult { Value(f64), ChangeMode(Box<dyn CalculatorState>), NoOutput, Error(String),}This enum replaces the approach of having states call back into the calculator to change its state. In Rust, a state can’t mutably modify the calculator that owns it. That would require borrowing the calculator both immutably (through the state field) and mutably at the same time. Returning the state transition as data avoids this conflict entirely. This approach models the calculator as a finite state machine, where each mode is a state and InputResult::ChangeMode represents transitions between states.
The state interface defines the behaviors that vary between modes:
pub trait CalculatorState: Send { fn name(&self) -> &str;
fn handle_input( &self, input: &str, data: &mut CalculatorData, ) -> InputResult;
fn format_output(&self, value: f64) -> String { format!("{}", value) }
fn supported_operations(&self) -> &[&str] { &["+", "-", "*", "/"] }}The handle_input method processes user input and returns an InputResult. It operates on CalculatorData rather than the full Calculator. The Send bound ensures states can be safely transferred between threads. We include it because our calculator may be used in concurrent contexts where the state object needs to move between threads. Default implementations for format_output and supported_operations provide sensible defaults that states override when needed.
The calculator separates shared data from the state holder:
#[derive(Default)]pub struct CalculatorData { pub variables: HashMap<String, f64>, pub history: Vec<Calculation>,}
pub struct Calculator { state: Box<dyn CalculatorState>, data: CalculatorData,}Because state and data are separate fields, Rust allows borrowing them independently. The state is borrowed immutably while data is borrowed mutably. Using Box for dyn CalculatorState provides runtime polymorphism: we can swap states at runtime while the calculator treats them uniformly through the trait interface.
The Calculator delegates input processing to its current state and acts on the result:
impl Calculator { pub fn new() -> Self { Self { state: Box::new(StandardMode::new()), data: CalculatorData::default(), } }
pub fn process_input(&mut self, input: &str) -> Result<Option<f64>, String> { match self.state.handle_input(input, &mut self.data) { InputResult::Value(v) => Ok(Some(v)), InputResult::NoOutput => Ok(None), InputResult::ChangeMode(new_state) => { self.state = new_state; Ok(None) } InputResult::Error(e) => Err(e), } }
pub fn format_output(&self, value: f64) -> String { self.state.format_output(value) }}The process_input method delegates to the current state, then pattern-matches on the result. If the state signals a mode change, the calculator swaps in the new state. The state itself never touches the calculator. It returns data describing what should happen, and the calculator acts on it.
Implementing concrete states
Section titled “Implementing concrete states”Each calculator mode becomes a concrete state. Standard mode encapsulates basic calculator operation, including its own expression parser:
pub struct StandardMode { parser: ExpressionParser,}
impl StandardMode { pub fn new() -> Self { Self { parser: ExpressionParser::new(), } }
fn evaluate(&self, expr: &str, data: &mut CalculatorData) -> Result<f64, String> { // Evaluate the expression using the parser and variables let parsed = self.parser.parse(expr)?; parsed.evaluate(&data.variables) }}This isolation means we can modify standard mode’s parsing without affecting other modes.
The handle_input implementation handles mode switching, variable assignment, and expression evaluation:
impl CalculatorState for StandardMode { fn name(&self) -> &str { "Standard" }
fn handle_input(&self, input: &str, data: &mut CalculatorData) -> InputResult { let input = input.trim();
if input.starts_with("mode ") { return match create_mode(input.trim_start_matches("mode ").trim()) { Ok(state) => InputResult::ChangeMode(state), Err(e) => InputResult::Error(e), }; }
if let Some((name, expr)) = input.split_once('=') { return match self.evaluate(expr.trim(), data) { Ok(value) => { data.variables.insert(name.trim().to_string(), value); InputResult::Value(value) } Err(e) => InputResult::Error(e), }; }
match self.evaluate(input, data) { Ok(value) => InputResult::Value(value), Err(e) => InputResult::Error(e), } }}Mode switching uses a create_mode factory and returns InputResult::ChangeMode with the new state. Variable assignment evaluates the expression, stores the result, and returns the value. Plain expressions evaluate directly. Each path returns the appropriate InputResult variant. The calculator handles the rest.
Scientific mode adds trigonometric functions and maintains its own angle configuration:
pub struct ScientificMode { parser: ExpressionParser, angle_mode: AngleMode,}
impl ScientificMode { pub fn new() -> Self { Self { parser: ExpressionParser::new(), angle_mode: AngleMode::Radians, } }
fn to_radians(&self, angle: f64) -> f64 { match self.angle_mode { AngleMode::Radians => angle, AngleMode::Degrees => angle * std::f64::consts::PI / 180.0, } }}The angle mode is state-local data. It lives within ScientificMode rather than cluttering the shared CalculatorData. Only data common to all modes (variables, history) belongs in CalculatorData. This keeps states self-contained and makes adding new modes straightforward.
ScientificMode’s handle_input follows the same structure as StandardMode but adds angle mode transitions. When the user types “angle deg,” the state creates a new ScientificMode instance with a different configuration, which is essentially a sub-state within a state:
// Inside ScientificMode::handle_inputif input.starts_with("angle ") { let angle_mode = match input.trim_start_matches("angle ").trim() { "deg" => AngleMode::Degrees, "rad" => AngleMode::Radians, other => return InputResult::Error( format!("Unknown angle mode: {}", other) ), }; return InputResult::ChangeMode(Box::new(ScientificMode { parser: self.parser.clone(), angle_mode, }));}Scientific mode also overrides the default behavior for output formatting and available operations:
impl CalculatorState for ScientificMode { // name() and handle_input() as described above...
fn format_output(&self, value: f64) -> String { format!("{:e}", value) }
fn supported_operations(&self) -> &[&str] { &["+", "-", "*", "/", "sin", "cos", "tan", "log", "exp"] }}These overrides let each mode present the appropriate interface and output format to users. Standard mode shows decimal results; scientific mode uses scientific notation.
State transitions
Section titled “State transitions”The InputResult::ChangeMode variant makes transitions explicit and visible. All transition logic lives in the state implementations. The calculator itself doesn’t need to understand mode transitions. Invalid transitions are rejected with clear error messages, and states can perform cleanup before transitioning.
A mode factory centralizes state construction:
fn create_mode(name: &str) -> Result<Box<dyn CalculatorState>, String> { match name { "standard" => Ok(Box::new(StandardMode::new())), "scientific" => Ok(Box::new(ScientificMode::new())), "programmer" => Ok(Box::new(ProgrammerMode::new())), _ => Err(format!("Unknown mode: {}", name)), }}Both StandardMode and ScientificMode use this factory for mode switching, avoiding duplicated construction logic. Adding a new mode means adding one line to this factory and creating the new state type. Existing states don’t need modification.
When to use the State pattern
Section titled “When to use the State pattern”The State pattern fits scenarios where an object’s behavior depends on its state and must change at runtime based on that state. It’s appropriate when operations have large, multipart conditional statements that depend on the object’s state, when state-specific behavior should be encapsulated independently, or when state transitions follow complex rules.
In our calculator, the State pattern cleanly separates standard, scientific, and programmer modes. Adding a new mode, say, statistical or financial, means creating a new state implementation without modifying existing code. The pattern has given our calculator a professional feel where users can switch modes and get appropriate behavior for each context.
Note: For applications with very strict state machines
For applications with very strict state machines where invalid transitions should be caught at compile time rather than runtime, consider Rust’s TypeState pattern, which encodes states as type parameters. We’ll explore this approach in Chapter 10, Patterns That Leverage the Type System.
In the next section, we’ll explore the Memento pattern, which will allow users to save and restore calculator states, enabling features like checkpointing and session persistence.
Memento pattern: capturing and restoring state
Section titled “Memento pattern: capturing and restoring state”The Memento pattern allows us to save and restore an object’s state without exposing its internal structure. This pattern provides a way to implement features like undo/redo, save/load functionality, and state histories, all while maintaining encapsulation.
The need for state management
Section titled “The need for state management”Our calculator has become increasingly complex, with various components maintaining state: variables and their values, the history of calculations, the current evaluation strategy, the current calculator mode, and the undo/redo history.
While the Command pattern from the previous chapter allows us to undo and redo individual operations, we sometimes need more comprehensive state management. Users might want to save the entire calculator state before experimenting with different approaches, restore to a previously saved configuration, create named snapshots (like “before optimization” or “working version”), or save their session and resume it later.
The Memento pattern addresses these needs by externalizing an object’s state into a separate memento object. The originator (our Calculator) can create mementos containing its state and later restore from them. A caretaker manages mementos, storing, organizing, and providing them when needed, without understanding or modifying their contents.
We’ll implement this pattern in three parts: defining the memento that captures calculator state, modifying the calculator to create and restore from mementos, and building a caretaker that manages memento history.
Designing the memento
Section titled “Designing the memento”The CalculatorMemento struct captures everything needed to restore the calculator to a particular state:
#[derive(Clone)]pub struct CalculatorMemento { variables: HashMap<String, f64>, history: Vec<Calculation>, mode_name: String, // Simpler to store the mode name strategy_name: String,}The memento stores variables, calculation history, the current mode, and the name of the active evaluation strategy. We store the strategy name rather than the strategy itself because strategies might not be cloneable or serializable.
The memento’s constructor is private. Only the Calculator should create valid mementos:
impl CalculatorMemento { fn new( variables: HashMap<String, f64>, history: Vec<Calculation>, mode_name: String, strategy_name: String, ) -> Self { Self { variables, history, mode_name, strategy_name, } }}This privacy preserves encapsulation. External code can hold mementos and pass them around, but cannot create arbitrary mementos or modify their contents. The Calculator remains the authority on what constitutes valid state.
The Clone derive enables copying mementos when needed – for instance, when both undo and redo stacks need to hold the same snapshot.
Calculator as originator
Section titled “Calculator as originator”The Calculator creates mementos capturing its current state and restores from them:
impl Calculator { pub fn create_memento(&self) -> CalculatorMemento { CalculatorMemento::new( self.data.variables.clone(), self.data.history.clone(), self.state.name().to_string(), // Assuming the calculator has a strategy_name property or similar self.get_strategy_name(), ) }}Creating a memento clones the calculator’s state. This ensures the memento is independent. Subsequent changes to the calculator don’t affect saved mementos. The clone cost is the price of independence; for very large states, you might consider copy-on-write techniques.
Restoration replaces the calculator’s fields with the memento’s saved values. The strategy requires special handling. Since trait objects can’t be directly cloned or stored, we recreate the strategy through a factory using its saved name:
impl Calculator { pub fn restore_from_memento( &mut self, memento: CalculatorMemento, ) -> Result<(), String> { let CalculatorMemento { variables, history, mode_name, strategy_name } = memento;
self.data.variables = variables; self.data.history = history;
// Recreate the state from its name self.state = create_mode(&mode_name)?;
// Recreate the strategy from its name self.set_strategy_from_name(&strategy_name)?;
Ok(()) }}Restoration can fail: perhaps the saved strategy name is no longer recognized. So, we return Result rather than silently falling back to a default. This makes error handling explicit, allowing the caller to decide how to respond to a failed restoration.
Here we are using destructuring. The let { variables, history, mode_name, strategy_name } = memento; binds the individual fields to the variables that we can then assign.
Rust allows struct destructuring directly in function parameters, which can make code more concise. For example, a simpler restore function could destructure the memento in its signature:
fn restore_from_memento( &mut self, CalculatorMemento { variables, history, mode_name, .. }: &CalculatorMemento,) -> Result<(), String> { // ...}Each named field becomes a reference to the corresponding value inside the memento. Unfortunately, our full restore_from_memento needs to keep the parameter intact because it also passes the whole memento to create_state_from_memento, so destructuring in the parameter list would require an @ binding such as memento @ CalculatorMemento { .. } to retain access to the whole value. That adds complexity without much benefit here, but in functions that only access individual fields, parameter destructuring is a clean alternative to repeated memento. field access.
The caretaker
Section titled “The caretaker”The caretaker manages mementos without understanding their contents. It provides named state storage and undo/redo stacks:
pub struct MementoCaretaker { saved_states: HashMap<String, CalculatorMemento>, undo_history: Vec<CalculatorMemento>, redo_history: Vec<CalculatorMemento>,}
impl MementoCaretaker { pub fn new() -> Self { Self { saved_states: HashMap::new(), undo_history: Vec::new(), redo_history: Vec::new(), } }
pub fn save_state(&mut self, name: &str, memento: CalculatorMemento) { self.saved_states.insert(name.to_string(), memento); }
pub fn get_state(&self, name: &str) -> Option<&CalculatorMemento> { self.saved_states.get(name) }
pub fn save_for_undo(&mut self, memento: CalculatorMemento) { self.undo_history.push(memento); self.redo_history.clear(); }
// undo and redo methods below...}[figure outside: sequence diagram]
impl MementoCaretaker { pub fn undo(&mut self, current_state: CalculatorMemento) -> Option<CalculatorMemento> { if let Some(previous_state) = self.undo_history.pop() { // Save current state for potential redo self.redo_history.push(current_state); Some(previous_state) } else { None } }
pub fn redo(&mut self, current_state: CalculatorMemento) -> Option<CalculatorMemento> { if let Some(next_state) = self.redo_history.pop() { // Save current state for potential undo self.undo_history.push(current_state); Some(next_state) } else { None } }}Both undo and redo return Option. None signals an empty stack, letting the caller distinguish between a successful restoration and having nothing to undo or redo.
Integrating with the calculator
Section titled “Integrating with the calculator”With the pattern’s three roles defined (originator, memento, and caretaker), we integrate them into a single user-facing type that coordinates between them:
pub struct CorrectCalculator { calculator: Calculator, caretaker: MementoCaretaker, parser: ExpressionParser,}The CorrectCalculator owns both the calculator and the caretaker, keeping state management separate from mathematical computation.
When processing input, it automatically saves state for undo before making changes:
impl CorrectCalculator { pub fn process_input(&mut self, input: &str) -> Result<String, String> { // Save current state before making changes let current_state = self.calculator.create_memento();
// Process the input let result = self.process_input_internal(input);
// If successful, save the pre-change state for undo if result.is_ok() { self.caretaker.save_for_undo(current_state); }
result }}We save state before processing, not after. This means undo restores to the state before the operation, which matches user expectations.
Named save and restore operations let users create labeled snapshots. The save_state method captures the current state and hands it to the caretaker; restore_state retrieves a named snapshot and applies it:
impl CorrectCalculator { pub fn save_state(&mut self, name: &str) -> Result<String, String> { let memento = self.calculator.create_memento(); self.caretaker.save_state(name, memento); Ok(format!("State saved as '{}'", name)) }
pub fn restore_state(&mut self, name: &str) -> Result<String, String> { if let Some(memento) = self.caretaker.get_state(name).cloned() { self.calculator.restore_from_memento(memento)?; Ok(format!("State '{}' restored", name)) } else { Err(format!("No saved state named '{}'", name)) } }}Note the .cloned() call when retrieving the state. We need to own the memento to restore from it, but get_state returns a reference. Cloning creates an independent copy.
The CorrectCalculator’s undo and redo methods coordinate the full flow: capture the current state, ask the caretaker for the target state, and restore it. Each method snapshots the current state first, ensuring the caretaker always has the correct state to push onto the opposite stack:
impl CorrectCalculator { pub fn undo(&mut self) -> Result<String, String> { let current_state = self.calculator.create_memento();
if let Some(previous_state) = self.caretaker.undo(current_state) { self.calculator.restore_from_memento(previous_state)?; Ok("Operation undone".to_string()) } else { Err("Nothing to undo".to_string()) } }
pub fn redo(&mut self) -> Result<String, String> { let current_state = self.calculator.create_memento();
if let Some(next_state) = self.caretaker.redo(current_state) { self.calculator.restore_from_memento(next_state)?; Ok("Operation redone".to_string()) } else { Err("Nothing to redo".to_string()) } }}The Result<String, String> return type is simple but effective here. A production implementation might define a dedicated result type (such as an UndoResult enum) for richer feedback. The symmetry between undo and redo reflects the symmetry in the caretaker’s stack management. They’re mirror operations, each moving state from one stack to the other through the calculator.
Persistence with serialization
Section titled “Persistence with serialization”Mementos are natural candidates for serialization because they already encapsulate complete state in a single struct. Adding serde’s Serialize and Deserialize derives, along with the same derives on all types the memento contains, enables conversion to and from formats like JSON:
use serde::{Serialize, Deserialize};
#[derive(Clone, Serialize, Deserialize)]pub struct CalculatorMemento { variables: HashMap<String, f64>, history: Vec<Calculation>, mode_name: String, strategy_name: String,}With serialization in place, the calculator can save entire sessions to disk and load them back later, turning the Memento pattern into a persistence mechanism:
use std::fs::File;
impl CorrectCalculator { pub fn save_to_file(&self, path: &str) -> Result<String, String> { let memento = self.calculator.create_memento(); let file = File::create(path).map_err(|e| e.to_string())?; serde_json::to_writer(file, &memento).map_err(|e| e.to_string())?; Ok(format!("State saved to {}", path)) }
pub fn load_from_file(&mut self, path: &str) -> Result<String, String> { let file = File::open(path).map_err(|e| e.to_string())?; let memento: CalculatorMemento = serde_json::from_reader(file) .map_err(|e| e.to_string())?; self.calculator.restore_from_memento(memento)?; Ok(format!("State loaded from {}", path)) }}JSON serialization produces human-readable files, useful for debugging or manual editing. For more compact storage, the bincode crate (https://crates.io/crates/bincode) provides efficient binary serialization.
When to use the Memento pattern
Section titled “When to use the Memento pattern”The Memento pattern fits scenarios where you need to save and restore object state without violating encapsulation. It’s appropriate for implementing undo/redo beyond simple operation reversal, creating snapshots at significant points, supporting save/load functionality, and implementing checkpoints for recovery.
The pattern complements the Command pattern. Commands track individual operations and their inverses; mementos capture complete state. For our calculator, commands enable fine-grained undo of specific operations, while mementos enable coarse-grained restoration to saved checkpoints.
Consider memory usage when applying this pattern. Each memento clones the originator’s state, which can be expensive for large objects. Strategies to manage memory include limiting undo history depth, storing partial states (only the fields that actually changed) rather than full snapshots, using incremental deltas for frequent saves, and employing copy-on-write for large immutable portions of state.
Rust’s ownership model makes memento implementation straightforward. Mementos own their data (via cloning), so there are no concerns about dangling references or shared mutation. The privacy of the memento constructor, enforced by Rust’s module system, ensures only the originator creates valid mementos.
In the next section, we’ll explore the Observer pattern, which establishes a communication mechanism between objects, allowing our calculator to react to changes in variables or settings.
Observer pattern: reacting to changes
Section titled “Observer pattern: reacting to changes”The Observer pattern establishes a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. This pattern is fundamental to implementing event handling systems, reactive programming models, and components that need to stay synchronized.
The need for reactive components
Section titled “The need for reactive components”As our calculator has grown more complex, we’ve encountered scenarios where multiple components need to stay in sync. When a variable changes, expressions using that variable need to be recalculated. When the calculator mode changes, the user interface needs to update to show appropriate controls. When calculations complete, the history display needs to refresh. When errors occur, they need to be logged and displayed.
Without a proper pattern, implementing these connections leads to tight coupling. The variable storage would need to know about the user interface, the history, and every expression that might depend on a variable. Changing the user interface would require modifying the storage. Testing the storage would require setting up the user interface.
The Observer pattern decouples the subject (the object being observed) from its observers. The subject maintains a list of observers and notifies them of changes, but doesn’t know what they do with that information. Observers register themselves with subjects they care about and react when notified.
We’ll implement this pattern in three parts: defining an event-based notification system, building a subject that manages observers, and creating concrete observers that react to calculator events.
Designing an event-based observer
Section titled “Designing an event-based observer”Rather than having observers query the subject for what changed, we can use Rust’s enum system to describe events explicitly:
#[derive(Clone, Debug)]pub enum CalculatorEvent { VariableChanged(String, f64), ResultCalculated(f64, String), ModeChanged(String), Error(String),}Each variant carries the data observers need to react. VariableChanged carries the variable name and new value; ResultCalculated carries the result and the expression that produced it. This design eliminates downcasting. Observers pattern-match on events to extract the data they need.
The Observer interface is deliberately minimal – a single method that receives events by reference. The design choices in this trait address two common pitfalls of observer implementations in Rust:
pub trait Observer: Send + Sync { fn update(&self, event: &CalculatorEvent);}There are two important design choices here. First, update takes &self rather than &mut self. This avoids the borrow conflict that arises in classic implementations: if the subject holds observers and calls notify(&self), mutably borrowing observers inside an immutable borrow would require RefCell or similar workarounds. With &self, no interior mutability is needed.
Observers that do need mutable state can use Arc<Mutex<T>> internally for the specific fields that change.
Second, Send + Sync bounds ensure observers can be safely shared across threads. This is important for responsive user interfaces, where notifications might arrive from background computation threads.
The Subject interface manages observer registration and notification:
pub trait Subject { fn attach(&mut self, observer: Box<dyn Observer>) -> usize; fn detach(&mut self, observer_id: usize); fn notify(&self, event: &CalculatorEvent);}The attach method returns an ID for later removal. We use Box<dyn Observer> to store observers of different concrete types in the same collection. IDs avoid the need for PartialEq on trait objects, which Rust doesn’t support.
Implementing the subject
Section titled “Implementing the subject”The subject maintains a map of observers and dispatches events to all of them:
pub struct ObservableCalculator { observers: HashMap<usize, Box<dyn Observer>>, next_observer_id: usize,}
impl ObservableCalculator { pub fn new() -> Self { Self { observers: HashMap::new(), next_observer_id: 0, } }}Using a HashMap keyed by ID gives O(1) attachment and detachment. The next_observer_id counter uses a plain usize rather than AtomicUsize because attach() requires &mut self, which already guarantees exclusive access. If we needed to allow concurrent registration (with &self), we would switch to AtomicUsize. The subject owns its observers through Box, which is straightforward when observers exist to serve a specific subject. For observers shared across multiple subjects, Arc provides shared ownership.
The Subject implementation handles the mechanics of registration and notification. Attachment assigns a unique ID, detachment removes an observer by ID, and notification iterates through all observers:
impl Subject for ObservableCalculator { fn attach(&mut self, observer: Box<dyn Observer>) -> usize { let id = self.next_observer_id; self.observers.insert(id, observer); self.next_observer_id += 1; id }
fn detach(&mut self, observer_id: usize) { self.observers.remove(&observer_id); }
fn notify(&self, event: &CalculatorEvent) { for observer in self.observers.values() { observer.update(event); } }}To implement notification, we create a notify method that iterates through all observers and passes the event. Because both notify and update take immutable references, there’s no borrow conflict. The subject’s observer collection and each observer are all borrowed immutably at the same time, which Rust allows.
Creating concrete observers
Section titled “Creating concrete observers”Observers react to events through pattern matching. A display observer updates the user interface when the calculator state changes:
pub struct DisplayObserver { display: Arc<Mutex<dyn Display>>,}
impl DisplayObserver { pub fn new(display: Arc<Mutex<dyn Display>>) -> Self { Self { display } }}
impl Observer for DisplayObserver { fn update(&self, event: &CalculatorEvent) { let display = self.display.lock().unwrap();
match event { CalculatorEvent::ResultCalculated(result, _) => display.show_result(*result), CalculatorEvent::VariableChanged(name, value) => display.show_message(&format!("{} = {}", name, value)), CalculatorEvent::ModeChanged(mode) => display.show_message(&format!("Switched to {} mode", mode)), CalculatorEvent::Error(message) => display.show_error(message), } }}The Arc<Mutex<dyn Display>> enables thread-safe sharing of the display, which is important for responsive user interfaces where the display might be accessed from both user interface and calculation threads.
Note that our lock().unwrap() call will panic if the mutex is poisoned (which happens when a thread panics while holding the lock). In production code, you would handle this more gracefully, either by using lock().expect() with a descriptive message or by returning a Result and dealing more gracefully with the PoisonError. We use unwrap() here for brevity, but lock poisoning, while less common, does really happen in multi-threaded code, so it deserves robust error handling.
Each event variant triggers different display behavior, all handled through a single match expression.
A logger observer records all events for debugging or audit trails:
pub struct LoggerObserver;
impl Observer for LoggerObserver { fn update(&self, event: &CalculatorEvent) { match event { CalculatorEvent::VariableChanged(name, value) => println!("[LOG] Variable: {} = {}", name, value), CalculatorEvent::ResultCalculated(result, expr) => println!("[LOG] Result: {} = {}", expr, result), CalculatorEvent::Error(msg) => println!("[LOG] Error: {}", msg), _ => {} } }}LoggerObserver is a zero-sized struct with no fields. It simply reacts to events by printing them. The wildcard _ => {} arm ignores events the logger doesn’t care about (such as ModeChanged, which the logger doesn’t log). Without it, the match would be non-exhaustive. Alternatively, we could list every variant explicitly, but the wildcard is more future-proof: if we add new event variants later, the logger still compiles without changes.
This demonstrates how different observers can selectively respond to different event types.
Note: A note about being careful
In the
update()implementation, we usedunwrap()on the lock. By doing that, we avoided all the work of returning theResultand then dealing with it up the chain. And why wouldn’t we? Lock poisoning “never happens” according to some people, and “you just have to be careful.”Sometimes it is possible to use an
unwrap()when you are absolutely certain that it will never panic. However, in my experience, one can be almost absolutely certain about things never happening, but then they have to deal with the consequences when they do happen.Have the patience to handle errors correctly now and use that patience to avoid regret.
Integrating observers with the calculator
Section titled “Integrating observers with the calculator”The calculator fires events at appropriate points during its operation. Each method that changes state creates the corresponding event variant and notifies observers, embedding the notification logic directly into the operations that trigger it:
pub struct CorrectCalculator { observable: ObservableCalculator, variables: HashMap<String, f64>, // ... other fields}
impl CorrectCalculator { pub fn set_variable(&mut self, name: &str, value: f64) { self.variables.insert(name.to_string(), value); self.observable.notify(&CalculatorEvent::VariableChanged( name.to_string(), value )); }
pub fn evaluate(&mut self, input: &str) -> Result<f64, String> { let result = self.evaluate_internal(input)?; self.observable.notify(&CalculatorEvent::ResultCalculated( result, input.to_string() )); Ok(result) }
// ...}Each operation creates the appropriate event variant and notifies observers. The calculator doesn’t know what observers exist or how they’ll react. It just fires events. Adding a new observer type requires no changes to the calculator.
With observers attached, the system becomes reactive. Every operation automatically triggers the appropriate responses in all registered observers without the calculator knowing anything about them:
let mut calculator = CorrectCalculator::new();
// Attach observerslet display = Arc::new(Mutex::new(ConsoleDisplay::new()));calculator.observable.attach(Box::new(DisplayObserver::new(Arc::clone(&display))));calculator.observable.attach(Box::new(LoggerObserver));
// Operations automatically notify all observerscalculator.set_variable("x", 5.0);// DisplayObserver shows: "Variable x = 5"// LoggerObserver prints: "[LOG] Variable: x = 5"
calculator.evaluate("x + 10").unwrap();// DisplayObserver shows the result// LoggerObserver prints: "[LOG] Result: x + 10 = 15"For more advanced reactive behavior, observers can implement dependent variables, where sum = x + y automatically recalculates when x or y changes. A dependent variable observer watches for VariableChanged events, checks whether the changed variable is a dependency, and triggers recalculation. The full implementation is in the code repository.
When to use the Observer pattern
Section titled “When to use the Observer pattern”The Observer pattern fits scenarios where one object’s state changes should trigger reactions in multiple other objects, especially when you don’t want the subject to know specifics about its observers. The pattern excels at implementing event systems, maintaining consistency between related objects (like model and view in the model-view-controller architecture), and building reactive data pipelines.
Consider the Observer pattern when changes to one object require changing others but you don’t know how many or exactly which objects, when an object should notify others without making assumptions about who they are, or when you want to add or remove reactivity at runtime.
The tradeoffs include potential for unexpected cascading updates and difficulty debugging notification chains. Using Rust’s built-in features with an event-based approach mitigates some of these concerns: events carry explicit data (making it clear what changed), pattern matching makes observer logic visible, and the type system ensures observers handle the event types they care about.
For concurrent applications, channels (such as std::sync::mpsc) offer an alternative to the Mutex-based approach we used in DisplayObserver. Channels naturally decouple the sender (subject) from the receiver (observer) and avoid the need for shared mutable state entirely. In async contexts, the Observer pattern maps naturally onto runtimes like Tokio using broadcast channels or the Notify primitive. The choice between Mutex-based observers, channel-based observers, and async alternatives depends on your application’s concurrency model.
In the next section, we’ll explore the Visitor pattern, which enables operations across an object structure without modifying its implementation.
Visitor pattern: separating algorithms from structure
Section titled “Visitor pattern: separating algorithms from structure”Throughout our calculator’s development, we’ve built an increasingly complex expression tree system representing mathematical calculations. As the calculator evolved to incorporate different modes and features, we discovered the need to apply various operations to these expression trees, including optimization, validation, transformation, and analysis. But how do we add these operations without continuously modifying our expression structs?
The Visitor pattern provides an elegant solution by separating operations from the object structure they operate on. It allows you to define new operations without changing the implementations of the elements on which they operate, effectively letting you add new behaviors to existing structs without modifying them.
The challenge of operating on expression trees
Section titled “The challenge of operating on expression trees”Our calculator’s expression tree represents mathematical expressions through a hierarchy of objects. The expression “3 * (x + 2)” becomes a tree with multiplication at the root, a number (3) as the left child, and addition as the right child, which has a variable (x) and a number (2) as its children.
We want to perform operations like optimizing expressions (replacing “x * 0” with “0”), validating expressions (checking for division by zero), collecting variable dependencies, and formatting expressions into different notations. We could add methods for each operation to every expression struct:
pub trait Expression { fn evaluate(&self, vars: &HashMap<String, f64>) -> Result<f64, String>; fn optimize(&self) -> Box<dyn Expression>; fn validate(&self) -> Result<(), String>; fn get_variables(&self) -> HashSet<String>; fn to_latex(&self) -> String; // More methods for each new operation...}This approach violates the open/closed principle. Every new operation requires modifying the Expression trait and every type that implements it. The expression types become cluttered with operations that are secondary to their core purpose of representing mathematical structure. Testing becomes difficult because each expression type bundles many unrelated behaviors.
The Visitor pattern separates these concerns. Expression types focus solely on structure, meaning what kind of expression they represent and what children they have. Operations live in separate visitor types, each implementing a complete algorithm that traverses the expression tree.
Designing the visitor interface
Section titled “Designing the visitor interface”The Visitor pattern requires two interfaces: one for visitors that perform operations, and one for elements that accept visitors. First, for performing operations, we can define a visitor trait for expressions:
pub trait ExpressionVisitor { fn visit_number(&mut self, number: &NumberExpression) -> Result<(), String>; fn visit_variable(&mut self, variable: &VariableExpression) -> Result<(), String>; fn visit_binary_op(&mut self, op: &BinaryOperation) -> Result<(), String>; fn visit_function(&mut self, func: &FunctionCall) -> Result<(), String>;}The visitor trait has a method for each expression type in our hierarchy. Rather than having expressions implement operations, the visitor implements handling for each expression type. When we add a new operation, we create a new visitor type. No changes to expressions are required.
The element interface forms the other half of the double dispatch. Each element type implements accept to call the appropriate visitor method, bridging the gap between the element’s concrete type and the visitor’s operation:
pub trait Visitable { fn accept(&self, visitor: &mut dyn ExpressionVisitor) -> Result<(), String>;}Each expression type implements accept by calling the appropriate visitor method. This is called double dispatch because two method calls are needed to select the right behavior. The first dispatch occurs on the element: calling accept on a NumberExpression routes to NumberExpression’s accept implementation. The second dispatch is on the visitor: inside accept, calling visitor.visit_number(self) routes to the specific visitor’s handling of numbers. Neither dispatch alone is sufficient. Without accept, the caller would need to downcast the expression to determine its type; without the specific visit_* methods, the visitor couldn’t specialize behavior per expression type. The double-dispatch mechanism ensures the correct visitor method is called based on both the expression type and the visitor type.
Implementing Visitable for expression types
Section titled “Implementing Visitable for expression types”Each expression type’s accept implementation is straightforward. It calls the visitor method corresponding to its type:
impl Visitable for NumberExpression { fn accept(&self, visitor: &mut dyn ExpressionVisitor) -> Result<(), String> { visitor.visit_number(self) }}
impl Visitable for VariableExpression { fn accept(&self, visitor: &mut dyn ExpressionVisitor) -> Result<(), String> { visitor.visit_variable(self) }}Leaf nodes simply delegate to the matching visitor method, since there are no children to traverse. The visitor receives a reference to the concrete type, giving the visitor access to all fields without downcasting.
For composite expressions, we visit children before the node itself, enabling bottom-up processing:
impl Visitable for BinaryOperation { fn accept(&self, visitor: &mut dyn ExpressionVisitor) -> Result<(), String> { self.left.accept(visitor)?; self.right.accept(visitor)?; visitor.visit_binary_op(self) }}
impl Visitable for FunctionCall { fn accept(&self, visitor: &mut dyn ExpressionVisitor) -> Result<(), String> { self.argument.accept(visitor)?; visitor.visit_function(self) }}This ordering, children before parent, enables bottom-up processing. The visitor sees leaf nodes first, building up information before seeing the operations that combine them. For top-down processing, we’d call the visitor method before visiting children.
We also update our Expression trait to require Visitable:
pub trait Expression: Visitable { fn evaluate(&self, variables: &HashMap<String, f64>) -> Result<f64, String>; fn clone_boxed(&self) -> Box<dyn Expression>; fn to_string(&self) -> String;}This ensures every expression can be visited, making visitors universally applicable to our expression hierarchy.
Creating concrete visitors
Section titled “Creating concrete visitors”With the infrastructure in place, we’ll implement visitors for specific operations. Each visitor encapsulates a complete algorithm.
Variable dependency collector
Section titled “Variable dependency collector”A simple visitor collects all variables an expression depends on. The collector maintains a HashSet of variable names (rather than a Vec) because an expression such as "x + x * y" should list x only once. The HashSet automatically deduplicates variable names as it accumulates dependencies during tree traversal:
use std::collections::HashSet;
pub struct VariableDependencyCollector { dependencies: HashSet<String>,}
impl VariableDependencyCollector { pub fn new() -> Self { Self { dependencies: HashSet::new() } }
pub fn dependencies(&self) -> &HashSet<String> { &self.dependencies }}The visitor maintains state, specifically the set of discovered dependencies, across its traversal. Each visit method contributes to this accumulated state:
impl ExpressionVisitor for VariableDependencyCollector { fn visit_number(&mut self, _: &NumberExpression) -> Result<(), String> { // Numbers have no variable dependencies Ok(()) }
fn visit_variable(&mut self, var: &VariableExpression) -> Result<(), String> { self.dependencies.insert(var.name.clone()); Ok(()) }
fn visit_binary_op(&mut self, _: &BinaryOperation) -> Result<(), String> { // Dependencies already collected from children Ok(()) }
fn visit_function(&mut self, _: &FunctionCall) -> Result<(), String> { // Dependencies already collected from argument Ok(()) }}The _: &NumberExpression syntax uses an underscore to indicate that the parameter is intentionally unused. The method must accept the parameter to satisfy the trait interface, but since numbers have no dependencies to collect, we discard it.
Because we visit children before parents, by the time visit_binary_op is called, both operands’ dependencies have already been collected. The visitor method for composite nodes often does nothing; the work has already been performed during child visits.
Expression optimizer
Section titled “Expression optimizer”A more sophisticated visitor optimizes expressions by applying algebraic simplifications:
pub struct ExpressionOptimizer { optimized: bool, replacements: HashMap<String, Box<dyn Expression>>,}
impl ExpressionOptimizer { pub fn new() -> Self { Self { optimized: false, replacements: HashMap::new(), } }
pub fn was_optimized(&self) -> bool { self.optimized }
pub fn get_replacement(&mut self, key: &str) -> Option<Box<dyn Expression>> { self.replacements.remove(key) }
fn is_zero(expr: &dyn Expression) -> bool { // Check if expression is constant zero // Simplistic implementation expr.to_string() == "0" }
fn is_one(expr: &dyn Expression) -> bool { // Check if expression is constant one expr.to_string() == "1" }}The leaf node visitors are trivial since numbers and variables are already in their simplest form. The optimization logic lives in visit_binary_op, which checks for algebraic simplifications:
impl ExpressionVisitor for ExpressionOptimizer { fn visit_number(&mut self, _: &NumberExpression) -> Result<(), String> { Ok(()) }
fn visit_variable(&mut self, _: &VariableExpression) -> Result<(), String> { Ok(()) }
fn visit_binary_op(&mut self, op: &BinaryOperation) -> Result<(), String> { match op.operator { Operator::Multiply => { if Self::is_zero(&*op.left) || Self::is_zero(&*op.right) { self.optimized = true; self.replacements.insert( op.to_string(), Box::new(NumberExpression::new(0.0)) ); } else if Self::is_one(&*op.left) { self.optimized = true; self.replacements.insert( op.to_string(), op.right.clone_boxed() ); } else if Self::is_one(&*op.right) { self.optimized = true; self.replacements.insert( op.to_string(), op.left.clone_boxed() ); } } Operator::Add => { if Self::is_zero(&*op.left) { self.optimized = true; self.replacements.insert( op.to_string(), op.right.clone_boxed() ); } else if Self::is_zero(&*op.right) { self.optimized = true; self.replacements.insert( op.to_string(), op.left.clone_boxed() ); } } _ => {} } Ok(()) }
fn visit_function(&mut self, func: &FunctionCall) -> Result<(), String> { if func.function == Function::Sin && Self::is_zero(&*func.argument) { self.optimized = true; self.replacements.insert( func.to_string(), Box::new(NumberExpression::new(0.0)) ); } Ok(()) }}The multiply-by-zero case demonstrates the approach: detect the pattern, mark the optimization flag, and record a replacement mapping. The x * 1 and 1 * x cases follow the same structure, replacing the expression with the non-identity operand. Similar rules apply for addition with zero and other algebraic identities.
Function optimization applies analogous simplifications to known mathematical identities.
Unlike the dependency collector which only reads data, the optimizer builds a replacement map. Some visitors accumulate information; others construct transformed output. Note that this visitor doesn’t modify expressions in place. Rust’s ownership model discourages in-place mutation of shared structures. Instead, the optimizer records replacements that the caller can apply to create a new, optimized expression tree. This immutable approach aligns with functional programming principles and avoids the complexity of modifying borrowed data.
Using visitors in the calculator
Section titled “Using visitors in the calculator”Integrating visitors into the calculator is straightforward. The dependency collector creates a visitor, passes it to the expression, and extracts the accumulated results:
impl Calculator { pub fn get_expression_dependencies( &self, expr: &dyn Expression ) -> HashSet<String> { let mut collector = VariableDependencyCollector::new(); if let Err(e) = expr.accept(&mut collector) { eprintln!("Error collecting dependencies: {}", e); return HashSet::new(); } collector.dependencies().clone() }}The pattern is create–visit–extract: create a visitor, pass it through the expression tree via accept, then retrieve the accumulated results. Error handling wraps the traversal. If any node’s accept fails, we log the error and return an empty set rather than propagating the failure.
The optimization method follows the same create–visit–extract pattern, but checks whether any optimizations were found before returning a replacement:
impl Calculator { pub fn optimize_expression( &self, expr: &dyn Expression ) -> Option<Box<dyn Expression>> { let mut optimizer = ExpressionOptimizer::new(); if let Err(e) = expr.accept(&mut optimizer) { eprintln!("Error during optimization: {}", e); return None; }
if optimizer.was_optimized() { optimizer.get_replacement(&expr.to_string()) } else { None } }}The calculator doesn’t know what visitors exist or how they work. It just passes expressions to them. Adding a new visitor (perhaps for expression complexity analysis or LaTeX conversion) requires no changes to the calculator or expression types.
Optimization integrates naturally into the evaluation pipeline. We attempt to optimize first, then evaluate whichever expression we end up with, either the original or the optimized replacement:
impl Calculator { pub fn evaluate_optimized(&self, input: &str) -> Result<f64, String> { let expr = self.parser.parse(input)?;
// Try to optimize first let expr_to_evaluate = self.optimize_expression(&*expr) .unwrap_or_else(|| expr.clone_boxed());
expr_to_evaluate.evaluate(&self.data.variables) }}The optimized expression (if optimization found improvements) or the original expression gets evaluated. The caller doesn’t need to know whether optimization occurred.
When to use the Visitor pattern
Section titled “When to use the Visitor pattern”The Visitor pattern fits when you have a stable structure with many operations. Our expression tree is a good example: the types of expressions (numbers, variables, binary operations, functions) change rarely, but we frequently add new ways to process them.
The pattern also suits scenarios where operations need to access concrete types. Each visitor method receives the specific expression type, enabling type-specific logic without downcasting. This is the double-dispatch benefit: both the element and visitor types influence the method called.
Consider the Visitor pattern when you find yourself adding unrelated methods to classes just because they share a structure, when related operations are scattered across many types, or when you want to add operations without recompiling the element classes.
The tradeoff is that adding new element types requires updating all visitors. If your hierarchy changes frequently, visitors become a maintenance burden. For our calculator, expression types are stable while operations evolve, making Visitor an excellent fit.
Rust’s implementation differs from object-oriented languages in a few ways. We can’t use method overloading for the visit methods, so we use explicit names like visit_number and visit_binary_op. Mutation during traversal requires careful handling due to borrowing rules. Our optimizer builds a replacement map rather than modifying in place. These constraints guide us toward cleaner designs.
With the patterns from this chapter, our Correct Calculator project is now complete. From its humble beginnings as a simple expression evaluator in Chapter 5, Creational Patterns: Making Things, it has evolved into a sophisticated application.
Summary
Section titled “Summary”In this chapter, we explored the second set of behavioral design patterns and applied them to our calculator project. These patterns have transformed our calculator from a simple expression evaluator into a sophisticated, feature-rich application with reactive components, state persistence, and intelligent expression handling.
The Iterator pattern provided us with a powerful mechanism for traversing collections in a consistent way without exposing their internal structure. In Rust, this pattern is deeply integrated into the language through the Iterator trait. We implemented custom iterators for our calculator’s calculation history, allowing clients to process past calculations with clean, functional-style code. The pattern’s implementation in Rust showcases how the language’s zero-cost abstractions enable high-level programming without runtime performance penalties.
The State pattern allowed our calculator to alter its behavior based on its current mode. By encapsulating each mode as a separate type implementing the CalculatorState trait, we eliminated complex conditional logic and made our calculator easily extensible with new modes like scientific and programmer calculators. This pattern demonstrates how Rust’s trait system provides a clean alternative to the inheritance-based implementations common in other languages.
The Memento pattern gave our calculator the ability to save and restore its state, enabling features like named configurations, comprehensive undo/redo functionality, and session persistence. Our implementation showed how to externalize complex state without breaking encapsulation, using Rust’s ownership model to ensure that mementos remain independent and immutable.
The Observer pattern transformed our calculator into a reactive system where changes to one component automatically trigger updates in dependent components. We implemented this pattern to create a spreadsheet-like dependency system for variables, automatic UI updates, and comprehensive logging. Our implementation highlighted how Rust’s ownership and borrowing rules influence the design of observer systems, leading to solutions that use Arc<Mutex<T>> for safe shared access across components.
The Visitor pattern allowed us to add new operations to our expression tree structure without modifying the expression types themselves. We implemented visitors for expression optimization, validation, and dependency analysis, demonstrating how the pattern enables separation of algorithms from the data structures they operate on. The implementation in Rust showed how traits and runtime type information provide a type-safe approach to the classic double-dispatch problem.
In the next part of the book, we’ll shift our focus to Rust-specific patterns and idioms that leverage the language’s type system, ownership model, and zero-cost abstractions. We’ll apply these patterns to a new project: building a microservice that will evolve across the remaining chapters.