Skip to content
ImagineWorld

Structural Patterns: Connecting and Aggregating Components

node_idnode-book_design-patterns-and-best-practices-in-rust_chapter-06-structural-patterns-connecting-and-aggregating-components
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num6
chapter_titleStructural Patterns: Connecting and Aggregating Components
pillar_membershipJ — architecture_design_craft
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 6 — Structural Patterns: Connecting and Aggregating Components

Section titled “Chapter 6 — Structural Patterns: Connecting and Aggregating Components”

Structural Patterns: Connecting and Aggregating Components

Section titled “Structural Patterns: Connecting and Aggregating Components”

In this chapter, we’ll explore structural design patterns in Rust and how they help us organize components into larger, more capable systems. In Chapter 5, Creational Patterns: Making Things, we used creational patterns to establish clean ways of constructing our calculator’s objects: builders for configuration, factories for token creation, and singletons for shared state.

Structural patterns pick up where creational patterns leave off. Once we have well-constructed objects, structural patterns define how those objects connect, wrap, and compose into complex structures while maintaining flexibility and type safety.

We’ll see how Rust’s features influence our approach to these patterns in significant ways. Ownership and borrowing eliminate entire categories of problems that traditional structural patterns were designed to solve. Smart pointers like Box, Rc, and Arc provide built-in structural composition. The trait system offers a natural mechanism for defining interfaces between components. In several cases, Rust’s language features provide built-in alternatives to classical patterns, allowing us to achieve the same goals with less code and stronger safety guarantees.

We’ll continue building on our Correct Calculator project, enhancing it with more sophisticated expression handling, better organization, and cleaner interfaces. We’ll use the Decorator pattern to add logging, timing, and caching capabilities to our expressions without modifying their core behavior. The Adapter pattern will help us integrate external mathematical libraries behind a uniform interface. A Facade will simplify calculator usage by hiding the complexity of multiple subsystems. The Composite pattern will give us a recursive expression tree for representing arbitrarily complex mathematical expressions. Finally, the Bridge pattern will separate our display logic from our evaluation logic, allowing each to vary independently.

In this chapter we’re going to cover the following main topics:

  • Proxies, decorators, and adapters
  • Facades
  • Composites
  • Flyweight
  • The Bridge pattern

These three patterns act as intermediaries that modify how we interact with objects. Each wraps an existing component to add behavior, control access, or translate interfaces. In traditional object-oriented languages, all three require substantial boilerplate. Rust’s language features often let us implement them more concisely, and in some cases eliminate the need for them entirely. In our calculator, we’ll use these patterns to add cross-cutting concerns like logging and caching, and to integrate external mathematical libraries behind a clean interface.

The Proxy pattern provides a placeholder or surrogate for another object to control access to it. Traditional uses include lazy initialization, access control, logging, and remote access. However, Rust’s ownership system and standard library often eliminate the need for hand-written proxies.

Consider lazy initialization, one of the most common proxy use cases. In many languages, you would write a proxy class that defers construction of an expensive resource (one that involves significant computation, file or network input/output (I/O), or large memory allocation) until first use, manually checking whether the inner object has been created on every method call. In Rust, the standard library provides LazyCell (and its thread-safe counterpart LazyLock) for exactly this purpose:

use std::cell::LazyCell;
struct Calculator {
expensive_ops: LazyCell<ExpensiveResource>,
}
impl Calculator {
fn new() -> Self {
Self {
expensive_ops: LazyCell::new(|| {
ExpensiveResource::load()
}),
}
}
fn compute(&self, input: f64) -> f64 {
self.expensive_ops.compute(input)
}
}

The LazyCell transparently handles deferred initialization. The first time expensive_ops is accessed, the closure runs and creates the resource. Subsequent accesses return the already-initialized value. There is no need for Option checks, no runtime borrow tracking, and no risk of accessing uninitialized memory.

Other common proxy scenarios are similarly covered by Rust’s built-in features. Access control is handled through module visibility (pub, pub(crate), pub(super)) rather than runtime proxy checks. Smart pointers like Box, Rc, and Arc serve as structural proxies that manage ownership and sharing. The Deref trait allows smart pointers to transparently delegate method calls to their inner types.

Because Rust provides these mechanisms at the language level, we rarely need to implement the Proxy pattern explicitly. Instead, we’ll focus our attention on the Decorator and Adapter patterns, which address needs that Rust’s built-in features don’t cover as directly.

The Decorator pattern: extensible expression behavior

Section titled “The Decorator pattern: extensible expression behavior”

The Decorator pattern lets us wrap an object in layers that add new behavior without modifying the original. As our calculator grows more sophisticated, we need to add cross-cutting concerns to expressions: logging for debugging, timing for performance analysis, caching for expensive computations, and range validation for safety. The naive approach would be to add these capabilities directly to every expression type. Consider what this looks like:

pub trait Expression {
fn evaluate(&self, vars:&HashMap<String, f64>) -> Result<f64, String>;
fn to_string(&self) -> String;
fn evaluate_with_logging(&self, vars:&HashMap<String, f64>) -> Result<f64, String>;
fn evaluate_with_timing(&self, vars:&HashMap<String, f64>) -> Result<f64, String>;
fn evaluate_with_caching(&self, vars:&HashMap<String, f64>) -> Result<f64, String>;
}

This bloated trait violates the single responsibility principle. Every expression type, whether it’s a simple NumberExpression or a complex BinaryOperation, must implement methods for concerns that have nothing to do with expression evaluation. Adding a new concern means modifying the trait and every implementor. Worse, combining concerns (logging with timing or caching with validation) requires even more methods, leading to a combinatorial explosion. With four concerns and the ability to combine them, we’d need fifteen additional methods to cover every combination.

The Decorator pattern solves this by wrapping expressions in layers that each handle one concern. Each decorator implements the same Expression trait, delegating the core work to an inner expression while adding its own behavior before or after. Decorators can be stacked in any combination without modifying the original expression types. In Rust, this approach aligns naturally with the trait object system: a decorator wraps a Box<dyn Expression> and itself implements Expression, making the wrapping invisible to callers.

Our Expression trait defines the core interface that both concrete expressions and decorators will implement:

pub trait Expression {
fn evaluate(
&self,
variables:&HashMap<String, f64>,
) -> Result<f64, String>;
fn to_string(&self) -> String;
fn precedence(&self) -> u8 {
0
}
}

The trait is deliberately minimal. The evaluate method takes a shared reference to a HashMap of variable bindings and returns either a computed value or an error message.

The Decorator pattern in Rust uses trait objects and composition. Each decorator holds a Box<dyn Expression> for the wrapped expression, which allows it to decorate any type that implements Expression.

Here is the foundation for our logging decorator, starting with a Logger trait and the LoggingExpression struct:

pub trait Logger {
fn log(&self, message: &str);
}
pub struct ConsoleLogger;
impl Logger for ConsoleLogger {
fn log(&self, message: &str) {
println!("[LOG] {}", message);
}
}
pub struct LoggingExpression {
inner: Box<dyn Expression>,
logger: Box<dyn Logger>,
}

Notice that the Logger is itself a trait object, which means we can swap in different logging backends (console, file, network) without changing the decorator. The LoggingExpression holds both the expression it decorates and the logger it uses, composing two independent abstractions.

Each decorator implements Expression, delegating to the inner expression and adding its own behavior. Let’s walk through three decorators that demonstrate different aspects of the pattern.

The LoggingExpression logs the expression being evaluated and its result:

impl Expression for LoggingExpression {
fn evaluate(
&self,
variables:&HashMap<String, f64>,
) -> Result<f64, String> {
self.logger.log(
&format!("Evaluating: {}",
self.inner.to_string())
);
let result = self.inner.evaluate(variables);
match &result {
Ok(val) => self.logger.log(
&format!("Result: {}", val)
),
Err(err) => self.logger.log(
&format!("Error: {}", err)
),
}
result
}
fn to_string(&self) -> String {
self.inner.to_string()
}
fn precedence(&self) -> u8 {
self.inner.precedence()
}
}

The evaluate method wraps the inner expression’s evaluation with log messages. It logs the expression string before evaluation, delegates to the inner expression, and then logs the outcome (whether success or error). The inner expression’s result passes through unchanged.

The remaining trait methods delegate directly to the inner expression. This delegation is critical. It makes the decorator transparent to any code that doesn’t care about logging. A function that calls to_string() on a LoggingExpression gets the same result as calling it on the unwrapped expression. This transparency is the key property that allows decorators to be stacked: any code that works with the Expression trait will work identically whether it receives a raw expression or one wrapped in any number of decorators.

The TimingExpression follows the same structure as the logging decorator, measuring how long evaluation takes:

pub struct TimingExpression {
inner: Box<dyn Expression>,
}
impl Expression for TimingExpression {
fn evaluate(
&self,
variables: &HashMap<String, f64>,
) -> Result<f64, String> {
let start = Instant::now();
let result = self.inner.evaluate(variables);
let duration = start.elapsed();
println!("Evaluation took: {:?}", duration);
result
}
fn to_string(&self) -> String {
self.inner.to_string()
}
fn precedence(&self) -> u8 {
self.inner.precedence()
}
}

The decorator captures the current time with Instant::now() before delegating to the inner expression, then prints the elapsed duration after evaluation completes. Like LoggingExpression, the to_string and precedence methods delegate directly to the inner expression, maintaining decorator transparency.

The pattern is consistent enough that you could write a macro to generate the boilerplate delegation methods, though for clarity we implement each decorator explicitly in the code repository.

The caching decorator with interior mutability

Section titled “The caching decorator with interior mutability”

The CachingExpression introduces an interesting Rust challenge. Caching requires storing a result, which involves mutating internal state (storing the computed result so future calls can return it without re-evaluating), but evaluate takes &self, not &mut self. This is where interior mutability comes in:

pub struct CachingExpression {
inner: Box<dyn Expression>,
last_result: RefCell<Option<f64>>,
}
impl CachingExpression {
pub fn new(inner: Box<dyn Expression>) -> Self {
Self {
inner,
last_result: RefCell::new(None),
}
}
pub fn invalidate_cache(&self) {
*self.last_result.borrow_mut() = None;
}
}

The RefCell<Option<f64>> allows us to mutate the cached value through a shared reference. This is a deliberate trade-off: we move borrow checking from compile time to runtime in exchange for the ability to cache results without changing the Expression trait’s signature.

It is important to understand what runtime borrow checking means in practice: if code calls borrow_mut() while an immutable borrow (from borrow()) is still active, the program will panic.

In our CachingExpression, we are careful to ensure that the immutable borrow in the cache check (the if let Some(result) line) is dropped before we call borrow_mut() to store a new result. If we accidentally held both borrows simultaneously, we would get a runtime panic instead of a compile-time error. This is the core risk of RefCell: it trades the compiler’s safety net for flexibility, and the programmer must ensure correct usage.

The Expression implementation checks the cache before delegating:

impl Expression for CachingExpression {
fn evaluate(
&self,
variables: &HashMap<String, f64>,
) -> Result<f64, String> {
if let Some(result) = *self.last_result.borrow() {
return Ok(result);
}
let result = self.inner.evaluate(variables)?;
*self.last_result.borrow_mut() = Some(result);
Ok(result)
}
fn to_string(&self) -> String {
self.inner.to_string()
}
fn precedence(&self) -> u8 {
self.inner.precedence()
}
}

The expression *self.last_result.borrow() chains three operations. First, self.last_result accesses the RefCell<Option<_>> field. Then .borrow() obtains a temporary shared reference to the inner Option, returning a Ref<Option<_>> smart pointer. Finally, the leading * dereferences that Ref to reach the Option itself, which we can then pattern-match with if let Some(result). The borrow is dropped at the end of the if let block, which is what makes it safe to call borrow_mut() a few lines later when we store the result.

On the first call, the cache is empty, so we evaluate the inner expression and store the result. Subsequent calls return the cached value immediately. The invalidate_cache method allows callers to force re-evaluation when variables change.

This pattern of using RefCell for interior mutability within decorators is common in Rust when the trait interface uses shared references. Use it judiciously: it is best suited for simple caches and counters where the borrow scope is obvious and short-lived.

Our fourth decorator, RangeValidatingExpression, holds minimum and maximum bounds alongside the inner expression. Its evaluate method delegates to the inner expression, then checks whether the result falls within the acceptable range, returning an Err if it does not. Unlike the other decorators that add behavior without affecting the result, RangeValidatingExpression can change the outcome: a successful evaluation becomes an error if the result is out of bounds. The to_string and precedence methods delegate to the inner expression, following the same pattern as our other decorators.

Because every decorator implements Expression and wraps a Box<dyn Expression>, we can compose them freely. Here is an expression wrapped with logging, timing, and range validation:

let expr = Box::new(NumberExpression::new(42.0));
let cached = Box::new(CachingExpression::new(expr));
let validated = Box::new(RangeValidatingExpression::new(
cached, 0.0, 100.0,
));
let timed = Box::new(TimingExpression::new(validated));
let logged = LoggingExpression::new(
timed,
Box::new(ConsoleLogger),
);
let result = logged.evaluate(&variables);

When evaluate is called on the outermost decorator, the call flows inward through each layer: logging records the expression, timing starts the clock, range validation checks the bounds, caching checks for a stored result, and finally the inner expression computes the value. The result then flows back outward through each layer.

The call flow is shown in Figure 6.1.

Figure 6.1: Decorator call flow during expression evaluation (the caching decorator is omitted for brevity)

[figure outside: Figure 6.1]

The order of wrapping matters: in this example, the log output includes the timing information because logging wraps timing. Reversing the order would instead time the logging output itself.

The Adapter pattern: integrating external libraries

Section titled “The Adapter pattern: integrating external libraries”

With our decorator implementations complete, we can add logging, timing, caching, and validation to any expression by wrapping it in layers. But decorators assume that a common interface already exists. What happens when we need to integrate components that don’t share our Expression interface at all?

The Adapter pattern bridges incompatible interfaces by wrapping one interface behind another. Our calculator needs trigonometric functions, but different math libraries present different interfaces. One library might work only in radians, another only in degrees. Some return errors through exceptions (in other languages) or special values, while our calculator uses Rust’s Result type. Without an adapter, code that uses these libraries becomes littered with conversion logic:

fn calculate_sin(angle: f64, use_degrees: bool) -> f64 {
let radians = if use_degrees {
angle * std::f64::consts::PI / 180.0
} else {
angle
};
radians.sin()
}

Every call site must know about angle conversion. If we switch libraries or add a new one, we must update every location that performs trigonometric calculations.

The Adapter pattern solves this by defining a uniform interface for scientific operations and providing implementations that translate between that interface and each library’s specific API.

We start by defining the interface our calculator expects. The ScientificOperations trait specifies a clean API for trigonometric and logarithmic functions:

pub trait ScientificOperations {
fn sin(&self, angle: f64) -> f64;
fn cos(&self, angle: f64) -> f64;
fn tan(&self, angle: f64) -> f64;
fn log(&self, value: f64, base: f64) -> Result<f64, String>;
}

Our first implementation, StandardScientificOperations, uses Rust’s standard library math functions. It stores the current angle mode and handles conversion internally:

pub struct StandardScientificOperations {
pub angle_mode: AngleMode,
}
impl ScientificOperations for StandardScientificOperations {
fn sin(&self, angle: f64) -> f64 {
match self.angle_mode {
AngleMode::Radians => angle.sin(),
AngleMode::Degrees => (angle * std::f64::consts::PI / 180.0).sin(),
}
}
fn cos(&self, angle: f64) -> f64 {
match self.angle_mode {
AngleMode::Radians => angle.cos(),
AngleMode::Degrees => (angle * std::f64::consts::PI / 180.0).cos(),
}
}
fn tan(&self, angle: f64) -> f64 {
match self.angle_mode {
AngleMode::Radians => angle.tan(),
AngleMode::Degrees => (angle * std::f64::consts::PI / 180.0).tan(),
}
}
}

Each trigonometric function follows the same pattern: check the angle mode, convert to radians if necessary, and call the corresponding standard library function. The match on AngleMode ensures that callers never need to think about conversion; they simply pass angles in whatever unit the calculator is configured for.

The log method demonstrates how the adapter also standardizes error handling:

impl ScientificOperations for StandardScientificOperations {
// ... trigonometric functions ...
fn log(&self, value: f64, base: f64) -> Result<f64, String> {
if value <= 0.0 {
return Err("Cannot take logarithm of non-positive number".to_string());
}
if base <= 0.0 || base == 1.0 {
return Err("Invalid logarithm base".to_string());
}
Ok(value.ln() / base.ln())
}
}

Where Rust’s built-in f64::ln() would return NaN for invalid inputs, our adapter returns descriptive Result errors that fit our calculator’s error model. This translation between different error-handling conventions is one of the most valuable aspects of the Adapter pattern.

To adapt an external library with a different API, we create an ExternalLibraryAdapter that implements the same ScientificOperations trait:

pub struct ExternalLibraryAdapter {
angle_mode: AngleMode,
}
impl ExternalLibraryAdapter {
pub fn new(angle_mode: AngleMode) -> Self {
Self { angle_mode }
}
fn convert_angle(&self, angle: f64) -> f64 {
match self.angle_mode {
AngleMode::Radians => angle,
AngleMode::Degrees => angle * std::f64::consts::PI / 180.0,
}
}
}

The ScientificOperations implementation uses this helper to translate each call:

impl ScientificOperations for ExternalLibraryAdapter {
fn sin(&self, angle: f64) -> f64 {
let converted = self.convert_angle(angle);
converted.sin() // Or a call to the actual external library here
}
// cos and tan follow the same pattern
// Default log implementation
fn log(&self, value: f64, base: f64) -> Result<f64, String> {
if value <= 0.0 {
return Err("Cannot take logarithm of non-positive number".to_string());
}
if base <= 0.0 || base == 1.0 {
return Err("Invalid logarithm base".to_string());
}
Ok(value.ln() / base.ln())
}
}

Each method converts the angle using the helper, then delegates to the underlying math function. The adapter encapsulates all the knowledge of how to translate between our calculator’s interface and the external library’s expectations. If we later switch to a different external library, we only need to update this one adapter; all calling code continues to work through the ScientificOperations trait.

One reason the adapter-as-wrapper approach is so common in Rust is the orphan rule: you can only implement a trait for a type if you own either the trait or the type. This means you cannot directly implement a foreign trait for a foreign type. The Adapter pattern, implemented as a newtype wrapper, is the standard workaround. You create a local struct that wraps the foreign type and implement the desired trait on your wrapper.

To connect our scientific operations to the expression system, we use ScientificFunctionExpression, which adapts a ScientificOperations implementation into something that works as an Expression:

pub struct ScientificFunctionExpression {
operation: Box<dyn Fn(f64) -> f64>,
arg_expression: Box<dyn Expression>,
description: String,
}
impl Expression for ScientificFunctionExpression {
fn evaluate(&self, variables: &HashMap<String, f64>) -> Result<f64, String> {
let arg_value = self.arg_expression.evaluate(variables)?;
Ok((self.operation)(arg_value))
}
fn to_string(&self) -> String {
format!("{}({})", self.description, self.arg_expression.to_string())
}
}

This struct uses a closure (Box<dyn Fn(f64) -> f64>) to capture a specific scientific operation. A factory method like new_sin shows how this works:

impl ScientificFunctionExpression {
pub fn new_sin(
sci_ops: Box<dyn ScientificOperations>,
arg: Box<dyn Expression>,
) -> Self {
let operation = Box::new(move |angle: f64| sci_ops.sin(angle));
Self {
operation,
arg_expression: arg,
description: "sin".to_string(),
}
}
}

The move keyword transfers ownership of the sci_ops trait object into the closure. Each call to the closure invokes sin on the captured provider. Factory methods for cos and tan follow the same pattern. This is a distinctly Rust approach. We are moving a Box<dyn ScientificOperations> into the closure, which captures ownership of the scientific operations provider. Closures with move semantics let us capture and encapsulate an entire trait object, creating a self-contained adapter that bridges two different abstractions. The ScientificOperations trait provides mathematical functions; the Expression trait provides the calculator’s evaluation pipeline. The ScientificFunctionExpression adapter sits between them, translating calls from one world into the other.

The Proxy, Decorator, and Adapter patterns each serve distinct roles as intermediaries, but knowing when to reach for each one in Rust requires understanding the alternatives the language provides.

For proxies, check first whether Rust’s built-in mechanisms solve your problem. LazyCell and LazyLock handle lazy initialization. Module visibility (pub, pub(crate)) handles access control. Smart pointers (Box, Rc, Arc) handle ownership proxying. The Deref trait lets smart pointers transparently forward method calls. In the rare cases where none of these suffice, a custom proxy in Rust looks much like a decorator: a struct wrapping the inner type via Box<dyn Trait>, implementing the same trait, and adding behavior in its method implementations.

For decorators, the pattern works well when you need to add behavior to trait objects dynamically. If you know at compile time which behaviors you need, consider using generics with trait bounds instead. A function like the following avoids the overhead of dynamic dispatch entirely:

fn evaluate_with_logging<E: Expression>(
expr: &E,
variables: &HashMap<String, f64>,
) -> Result<f64, String> {
println!("Evaluating: {}", expr.to_string());
let result = expr.evaluate(variables);
println!("Result: {:?}", result);
result
}

This generic version is monomorphized at compile time, meaning the compiler generates specialized code for each concrete Expression type it is called with. There is no vtable lookup and no heap allocation for the expression. The trade-off is that you lose the ability to stack decorators dynamically at runtime. For one-off decorators, a closure can be simpler than a dedicated struct: a function that wraps an Expression’s evaluate call with additional behavior and returns the result.

For adapters, Rust’s From and Into traits often provide a simpler alternative. Consider angle conversion:

struct Radians(f64);
struct Degrees(f64);
impl From<Degrees> for Radians {
fn from(d: Degrees) -> Self {
Radians(d.0 * std::f64::consts::PI / 180.0)
}
}
let angle: Radians = Degrees(90.0).into();

For simple type conversions like this, From/Into is cleaner than a full adapter struct. The Deref trait serves a different purpose: it lets a wrapper type transparently forward method calls to its inner type, acting as an implicit proxy. Use explicit adapter structs when you need to bridge complex interfaces, when the adaptation involves state (like our AngleMode), or when you need to adapt between two trait interfaces that you don’t control.

With our expressions now extensible through decorators and compatible with external libraries through adapters, let’s see how the Facade pattern can simplify access to all of these components.

The Facade pattern provides a simplified interface to a complex subsystem, hiding the details of multiple interacting components behind a single, easy-to-use API.

In our calculator, the subsystems include the expression parser, the variable store, scientific operations, evaluation strategies, and display formatting. Without a facade, every piece of code that uses the calculator must understand and coordinate all of these pieces individually.

Consider what it takes to evaluate a simple expression without a facade. The caller must create a parser, tokenize the input, build an expression tree, set up a variable map, and invoke evaluation:

let tokens = tokenize("2 + 3 * 4")?;
let expr = ExpressionParser::parse(&tokens)?;
let mut variables: HashMap<String, f64> = HashMap::new();
variables.insert("ans".to_string(), 0.0);
let result = expr.evaluate(&variables)?;

This is only the simple case. If we want to support trigonometric functions, we need to set up a ScientificOperations provider. If we want history tracking, we need to record each expression before evaluation. If we want special commands like sin 90, we need command parsing logic. Every consumer of the calculator must duplicate this orchestration logic, leading to inconsistency and making changes difficult. If we restructure the parser, change how variables are stored, or add a new subsystem, every call site must be found and updated.

The Facade pattern solves this by consolidating this complexity behind a single struct with a simple interface. Instead of orchestrating five subsystems, callers make a single method call and let the facade coordinate everything internally.

Our CalculatorFacade aggregates all the subsystems into one struct:

pub struct CalculatorFacade {
parser: ExpressionParser,
variables: HashMap<String, f64>,
scientific_ops: Box<dyn ScientificOperations>,
history: Vec<String>,
config: CalculatorConfig,
}
impl CalculatorFacade {
pub fn new(
scientific_ops: Box<dyn ScientificOperations>,
config: CalculatorConfig,
) -> Self {
Self {
parser: ExpressionParser,
variables: HashMap::new(),
scientific_ops,
history: Vec::new(),
config,
}
}
}

The facade owns its subsystems rather than borrowing them, which simplifies lifetime management. Owned fields eliminate the need for lifetime parameters on the struct, which matters more than you might expect. A struct with lifetime parameters cannot easily be stored in collections, shared across threads, or passed through async boundaries. By owning its data, CalculatorFacade is automatically Send and Sync (assuming its fields are), making it safe to use in multithreaded environments. This is a common pattern for SDK clients and API facades in production Rust code: own everything, and let the caller decide how to share the facade (via Arc, for example). The facade takes a Box<dyn ScientificOperations> so that callers can choose which scientific operations implementation to use (standard or external library adapter), without the facade needing to know or care which one it receives.

The primary method, evaluate, orchestrates the full pipeline:

impl CalculatorFacade {
pub fn evaluate(&mut self, expression: &str) -> Result<f64, String> {
self.history.push(expression.to_string());
if let Some(result) = self.handle_special_command(expression)? {
return Ok(result);
}
let tokens = self.tokenize(expression)?;
let expr = ExpressionParser::parse(&tokens)?;
let result = expr.evaluate(&self.variables)?;
self.variables.insert("ans".to_string(), result);
Ok(result)
}
fn handle_special_command(&self, expression: &str) -> Result<Option<f64>, String> {
// Implementation for special commands
Ok(None)
}
fn tokenize(&self, expression: &str) -> Result<Vec<Token>, String> {
// Tokenization logic
Ok(Vec::new())
}
}

Behind this single method call, the facade performs six distinct operations: recording the expression in history, checking for special commands (like sin or log), tokenizing the input string into tokens, parsing those tokens into an expression tree, evaluating the tree against stored variables, and saving the result as the ans variable for use in subsequent expressions. The caller sees none of this complexity. Changing how any of these steps works (for example, switching to a different parser) requires changes only inside the facade, not in any calling code.

The facade also provides domain-specific shortcuts for common calculations. Variable management is straightforward:

impl CalculatorFacade {
pub fn set_variable(&mut self, name: &str, value: f64) {
self.variables.insert(name.to_string(), value);
}
pub fn get_variable(&self, name: &str) -> Option<f64> {
self.variables.get(name).copied()
}
pub fn get_history(&self) -> &[String] {
&self.history
}
}

These methods provide controlled access to the facade’s internal state: set_variable writes to the HashMap, get_variable reads from it with an Option return for missing keys, and get_history returns a slice reference that lets callers inspect the history without being able to modify it.

Specialized mathematical operations hide multi-step calculations behind descriptive method names:

impl CalculatorFacade {
pub fn calculate_quadratic(
&self, a: f64, b: f64, c: f64,
) -> Result<(f64, f64), String> {
let discriminant = b * b - 4.0 * a * c;
if discriminant < 0.0 {
return Err("No real solutions".to_string());
}
let sqrt_d = discriminant.sqrt();
let x1 = (-b + sqrt_d) / (2.0 * a);
let x2 = (-b - sqrt_d) / (2.0 * a);
Ok((x1, x2))
}
pub fn calculate_pythagorean(
&self, a: f64, b: f64,
) -> f64 {
(a * a + b * b).sqrt()
}
}

These methods give callers a high-level, intention-revealing API. A user who wants to solve a quadratic equation doesn’t need to know how to construct the expression tree for the quadratic formula; the facade handles it.

Sharp-eyed readers will notice that neither method actually uses self. Strictly speaking, these could be associated functions (called via CalculatorFacade::calculate_quadratic(...) without an instance) or even standalone free functions. Placing them as methods on the facade is a convenience choice, not a necessity: it groups related mathematical operations in one place and lets callers discover them through the same type they already use for evaluate and set_variable.

It is a reasonable trade-off, but it is just as reasonable to disagree. If these methods become numerous enough to clutter the facade’s API, extracting them into a separate module or a dedicated MathUtils type would be a better design.

Rust alternatives: modules and crates as facades

Section titled “Rust alternatives: modules and crates as facades”

Rust’s module system provides a built-in mechanism that serves many of the same purposes as the Facade pattern. By controlling what a module or crate exports through pub use re-exports, you create a curated public API that hides internal complexity:

lib.rs
mod expression;
mod decorator;
mod adapter;
mod facade;
mod bridge;
mod config;
pub use expression::{Expression, NumberExpression};
pub use facade::CalculatorFacade;
pub use adapter::ScientificOperations;
pub use config::CalculatorConfig;

This lib.rs file acts as a facade at the crate level, whether the crate is published to crates.io or simply used as a local dependency within a workspace. Any code that depends on this crate sees only the types listed in the pub use declarations. The internal modules, their relationships, and their implementation details are hidden. The pub(crate) visibility modifier provides finer control, exposing items to other modules within the crate while keeping them hidden from external users.

Crate-level facades are particularly valuable for library authors. You can reorganize internal modules freely without breaking the public API, as long as the re-exported types remain available. This is exactly what the Facade pattern promises: a stable interface that shields callers from structural changes behind the scenes.

The distinction between module-level and struct-level facades maps to a useful rule of thumb. Use module-level facades (pub use) when you want to simplify the import experience for stateless functionality: types, functions, and traits. Use struct-level facades (like CalculatorFacade) when you need to coordinate stateful subsystems that share data across calls. In many applications, you’ll use both: a module-level facade to control what’s exported from your crate, and struct-level facades internally to orchestrate complex workflows.

Many experienced Rust developers consider the Facade pattern essential rather than optional: designing the public API first (“What should the caller be able to do?”) and then building the internals to support it leads to cleaner ownership boundaries and simpler interfaces.

Use the Facade pattern when a subsystem has grown complex enough that callers must coordinate multiple components to accomplish common tasks. The facade doesn’t add new functionality; it provides a more convenient entry point to existing functionality. If callers need fine-grained control, they can still access the underlying subsystems directly. A good facade should simplify the common case without preventing the advanced case.

Our facade simplifies calculator usage, but it still treats expressions as flat strings. To represent complex mathematical expressions with proper operator precedence and nested function calls, we need a recursive structure. That’s where the Composite pattern comes in.

The Composite pattern lets us treat individual objects and compositions of objects uniformly through a shared interface. In our calculator, this means a number, a variable, a binary operation like 2 + 3, and a deeply nested expression like sin(x + 1) * (y - 2) can all be evaluated, printed, and manipulated through the same Expression trait. The pattern creates a tree structure where leaf nodes and composite nodes implement the same interface.

Without the Composite pattern, handling expressions of varying complexity requires case-by-case logic. A flat approach might use an enum to distinguish simple operations:

fn evaluate_flat(
op: &str, a: f64, b: f64,
) -> Result<f64, String> {
match op {
"+" => Ok(a + b),
"-" => Ok(a - b),
"*" => Ok(a * b),
"/" if b != 0.0 => Ok(a / b),
"/" => Err("Division by zero".to_string()),
_ => Err(format!("Unknown operator: {}", op)),
}
}

This works for 2 + 3, but how do we represent 2 + 3 * 4 with correct precedence? Or sin(x + 1)? We would need separate handling for each level of nesting. Two-level expressions might look like evaluate_binary("+", 2.0, evaluate_binary("*", 3.0, 4.0)), but this approach doesn’t scale. Adding new expression types (function calls, conditional expressions, array indexing) requires modifying the evaluation function every time. The number of cases grows faster than the number of features, and testing becomes increasingly difficult because every combination must be handled explicitly.

The Composite pattern solves this elegantly by defining a tree where every node, whether leaf or branch, implements the same Expression trait. Think of how you learned operator precedence in school mathematics: given the expression 2 + 3 * b / 4, you first compute 3 * b, then divide by 4, then add 2. You are implicitly decomposing the flat expression into a tree of subexpressions: expr1 = 3 * b, expr2 = expr1 / 4, expr3 = 2 + expr2. The Composite pattern makes this decomposition explicit. A BinaryOperation holds two child expressions that could themselves be BinaryOperations, FunctionCalls, or any other expression type. Evaluation becomes recursive: each node evaluates its children and combines the results. The tree structure naturally encodes operator precedence and nesting, eliminating the need for separate handling of different expression depths.

In practice, a parser constructs these trees from text input. We will build a parser in Chapter 7, Behavioral Patterns 1: Taking Action, using the Template Method pattern. For now, we focus on the tree structure itself and construct trees manually to demonstrate the pattern.

We already defined the Expression trait in the Proxies, decorators, and adapters section. Now let’s implement the leaf nodes. A NumberExpression wraps a literal value:

pub struct NumberExpression {
pub value: f64,
}
impl NumberExpression {
pub fn new(value: f64) -> Self {
Self { value }
}
}
impl Expression for NumberExpression {
fn evaluate(
&self,
_variables:&HashMap<String, f64>,
) -> Result<f64, String> {
Ok(self.value)
}
fn to_string(&self) -> String {
format!("{}", self.value)
}
}

The NumberExpression is the simplest possible leaf node. It ignores the variables map entirely and always returns its literal value. The to_string method simply formats the number, producing a representation like "42" or "3.14".

A VariableExpression looks up a named value in the variable map:

pub struct VariableExpression {
pub name: String,
}
impl VariableExpression {
pub fn new(name: String) -> Self {
Self { name }
}
}
impl Expression for VariableExpression {
fn evaluate(
&self,
variables:&HashMap<String, f64>,
) -> Result<f64, String> {
variables.get(&self.name)
.copied()
.ok_or_else(|| format!(
"Undefined variable: {}", self.name
))
}
fn to_string(&self) -> String {
self.name.clone()
}
}

Both leaf nodes are simple: they hold a value (literal or named) and return it on evaluation. The key is that they implement the same Expression trait as our composite nodes, making them interchangeable in any context that expects an expression.

The composite node, BinaryOperation, is the heart of the Composite pattern. It holds two child expressions and an operator:

// Re-using the Operator enum from earlier examples
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Operator {
Add,
Subtract,
Multiply,
Divide,
Power,
}
pub struct BinaryOperation {
pub left: Box<dyn Expression>,
pub right: Box<dyn Expression>,
pub operator: Operator,
}
impl BinaryOperation {
pub fn new(left: Box<dyn Expression>, right: Box<dyn Expression>, operator: Operator) -> Self {
Self { left, right, operator }
}
}

The children are Box<dyn Expression> trait objects, which means each child can be any expression type: a number, a variable, another binary operation, or even a decorated expression. We use Box<dyn Expression> rather than generic type parameters because generics would make each BinaryOperation monomorphic (specialized to one concrete type) over its children’s types. A BinaryOperation<NumberExpression, NumberExpression> would be a different type from BinaryOperation<NumberExpression, VariableExpression>, preventing us from building heterogeneous trees where the left child is a NumberExpression and the right child is another BinaryOperation. Trait objects provide the dynamic dispatch needed for recursive, heterogeneous tree structures.

Recursive structures in Rust require heap allocation. This is because the compiler must know the size of every type at compile time. A struct that directly contains another instance of itself would have infinite size: a BinaryOperation containing a BinaryOperation containing a BinaryOperation, and so on. Box<dyn Expression> solves this by allocating children on the heap, giving each child a fixed-size pointer regardless of its actual type. This is a fundamental difference from languages with garbage collection, where recursive structures work without special consideration.

The Expression implementation evaluates both children recursively before combining them:

impl Expression for BinaryOperation {
fn evaluate(
&self,
variables: &HashMap<String, f64>,
) -> Result<f64, String> {
let l = self.left.evaluate(variables)?;
let r = self.right.evaluate(variables)?;
match self.operator {
Operator::Add => Ok(l + r),
Operator::Subtract => Ok(l - r),
Operator::Multiply => Ok(l * r),
Operator::Divide if r == 0.0 =>
Err("Division by zero".to_string()),
Operator::Divide => Ok(l / r),
Operator::Power => Ok(l.powf(r)),
}
}
fn to_string(&self) -> String {
// Simplistic implementation for illustration
format!("({} {:?} {})", self.left.to_string(), self.operator, self.right.to_string())
}
}

This recursive structure is what gives the Composite pattern its power. The ? operator on each child’s evaluate call propagates errors automatically, so a division-by-zero deep within a nested expression will bubble up to the top-level caller without any explicit error handling at intermediate nodes. The match on Operator maps each variant to its corresponding arithmetic operation, with special handling for division by zero.

FunctionCall is another composite node that applies a mathematical function to a single argument expression. Like BinaryOperation, it holds a child expression as a Box<dyn Expression>:

// Re-using the Function enum from earlier
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Function {
Sin,
Cos,
Tan,
Sqrt,
}
pub struct FunctionCall {
pub function: Function,
pub argument: Box<dyn Expression>,
}

The Function enum represents the available mathematical functions (Sin, Cos, Tan, Sqrt). The argument field can hold any expression type, which means we can represent both simple calls like sqrt(4) and nested calls like sin(x + 1).

The evaluate implementation first evaluates the argument, then applies the appropriate mathematical function:

impl Expression for FunctionCall {
fn evaluate(
&self,
variables: &HashMap<String, f64>,
) -> Result<f64, String> {
let val = self.argument.evaluate(variables)?;
match self.function {
Function::Sin => Ok(val.sin()),
Function::Cos => Ok(val.cos()),
Function::Tan => {
let hp = std::f64::consts::FRAC_PI_2;
if (val - hp).abs() % std::f64::consts::PI < 1e-10 {
Err("Tangent undefined at this value".into())
} else {
Ok(val.tan())
}
}
Function::Sqrt if val < 0.0 =>
Err("Cannot take square root of negative number".into()),
Function::Sqrt => Ok(val.sqrt()),
}
}
fn to_string(&self) -> String {
let func_name = match self.function {
Function::Sin => "sin",
Function::Cos => "cos",
Function::Tan => "tan",
Function::Sqrt => "sqrt",
};
format!("{}({})",
func_name,
self.argument.to_string()
)
}
fn precedence(&self) -> u8 {
4
}
}

Notice how Tan and Sqrt include domain validation. Tangent is undefined at odd multiples of π/2, and square root requires a non-negative argument. These checks transform mathematical edge cases into descriptive errors rather than returning NaN or Infinity.

The to_string method reconstructs the function call syntax for display purposes. The precedence of 4 (the highest) ensures that function calls are never unnecessarily parenthesized when displayed within larger expressions. Like BinaryOperation, FunctionCall demonstrates the recursive nature of the Composite pattern: the argument can itself be an arbitrarily complex expression tree, and the uniform Expression interface handles any depth of nesting.

With our leaf and composite nodes in place, we can construct expression trees that represent complex mathematical expressions. Here is how to build a tree for 2 + 3 * 4:

let multiply = Box::new(BinaryOperation::new(
Box::new(NumberExpression::new(3.0)),
Box::new(NumberExpression::new(4.0)),
Operator::Multiply,
));
let add = Box::new(BinaryOperation::new(
Box::new(NumberExpression::new(2.0)),
multiply,
Operator::Add,
));

The tree structure encodes operator precedence directly: multiplication is a child of addition, so it is evaluated first. There is no need for precedence tables or parenthesization rules during evaluation; the tree already represents the correct order of operations. In a parser (which isn’t shown here for brevity), precedence rules would determine how to construct the tree. Once constructed, the tree’s structure embodies those rules permanently.

Evaluating the tree is a single method call:

let variables = HashMap::new();
println!("Expression: {}", add.to_string());
match add.evaluate(&variables) {
Ok(result) => println!("Result: {}", result),
Err(e) => println!("Error: {}", e),
}

The evaluate call starts at the root Add node. The Add node asks its left child (the NumberExpression 2.0) to evaluate, which simply returns Ok(2.0). Then it asks its right child (the Multiply node) to evaluate. The Multiply node in turn evaluates its own children: NumberExpression(3.0) returns Ok(3.0), and NumberExpression(4.0) returns Ok(4.0). The Multiply node computes 3.0 * 4.0 = 12.0 and returns Ok(12.0) to the Add node. Finally, the Add node computes 2.0 + 12.0 = 14.0. The to_string method similarly traverses the tree recursively, reconstructing a human-readable representation with appropriate parenthesization based on precedence.

Figure 6.2: Expression tree example: 2 + 3 * 4

[figure outside: Figure 6.2]

Because all nodes implement Expression, decorators work seamlessly with composite trees. You can wrap the entire tree in a LoggingExpression to log the full evaluation, or wrap individual subtrees to log specific subexpressions. You can apply CachingExpression to an expensive subtree while leaving the rest uncached. This composability between the Composite and Decorator patterns is one of the strengths of defining a consistent trait interface that both patterns share.

The Composite pattern is most valuable when your data naturally forms a tree structure and you want to treat individual elements and compositions uniformly. Expression trees, file system hierarchies, UI widget trees, and organizational charts are all classic examples.

In Rust, an alternative to the Composite pattern is using enums. An Expr enum with variants for Number(f64), Variable(String), BinaryOp { left: Box<Expr>, ... }, and FunctionCall { ... } achieves a similar structure without trait objects. The enum approach is better when you know all expression types at compile time and want exhaustive pattern matching. The trait object approach is better when you need extensibility: new expression types can be added by implementing the Expression trait without modifying existing code.

Our calculator uses the trait object approach because it enables the Decorator pattern. If Expression were an enum, we couldn’t wrap arbitrary expressions in LoggingExpression or CachingExpression without adding decorator variants to the enum itself. This is a concrete example of the open/closed principle: the trait object approach is open to extension (new expression types and new decorators) without requiring modification of existing code.

Now that our expressions form rich, composable trees, let’s look at a pattern that addresses memory efficiency when these trees contain repeated values.

The Flyweight pattern minimizes memory usage by sharing common data across multiple objects. In languages where object allocation is expensive and objects carry significant overhead, flyweight factories that cache and reuse shared state can provide substantial savings. In Rust, however, the language and standard library provide built-in mechanisms that serve the same purpose, often more safely and efficiently than a hand-written flyweight implementation.

The most direct flyweight mechanism in Rust is the use of const and static values. Mathematical constants that many expressions share can be defined once and referenced everywhere:

use std::sync::OnceLock;
// Using the Config we defined earlier
#[derive(Clone, Default)]
pub struct CalculatorConfig {
pub precision: u32,
// ...
}
pub const DEFAULT_PRECISION: u32 = 10;
pub const MAX_PRECISION: u32 = 100;
static CONFIG: OnceLock<CalculatorConfig> = OnceLock::new();
pub fn get_global_config() -> &'static CalculatorConfig {
CONFIG.get_or_init(|| CalculatorConfig::default())
}

The OnceLock ensures the configuration is initialized exactly once and shared across all code that needs it. The &'static lifetime guarantees the reference is valid for the entire program. This achieves the flyweight goal of sharing immutable data without any custom factory or caching logic.

For shared ownership of data that needs to live as long as any of its users, Arc (atomic reference counting) provides thread-safe sharing:

use std::sync::Arc;
pub struct CalculatorPool {
shared_config: Arc<CalculatorConfig>,
}
impl CalculatorPool {
pub fn new(config: CalculatorConfig) -> Self {
Self {
shared_config: Arc::new(config),
}
}
pub fn get_config(&self) -> Arc<CalculatorConfig> {
Arc::clone(&self.shared_config)
}
}

Cloning an Arc increments a reference count rather than copying the underlying data. Multiple calculator instances can share the same configuration with negligible overhead. When the last Arc is dropped, the data is automatically cleaned up.

Beyond Arc, Rust offers several other mechanisms that serve flyweight purposes. Cow<'a, T> (clone-on-write) wraps data that is usually shared but occasionally needs modification; it borrows when possible and clones only when mutation is required. This is particularly useful for strings that are usually static but sometimes need runtime customization. For example, an error message might usually be a static string (“Division by zero”), but occasionally need to include a runtime value (“Unknown variable: x”). With Cow<'static, str>, the static case borrows the string at zero cost, while the dynamic case allocates only when necessary. String interning can be achieved through &'static str for compile-time strings or through shared Arc<str> values. The standard library’s HashMap can serve as a flyweight factory for caching and reusing computed values.

Rust’s ownership model can make the Flyweight pattern’s traditional distinction between intrinsic state (shared) and extrinsic state (unique) explicit at the type level. Shared state can use &, Arc, or 'static references. Unique state can use owned values. The compiler then enforces that shared data isn’t mutated without proper synchronization.

Rather than implementing a custom flyweight factory, Rust programmers should reach for these built-in tools. They provide the same memory savings with stronger safety guarantees and less code. The ownership model ensures that the distinction between shared and unique state is explicit and compiler-verified.

With memory efficiency handled by Rust’s built-in mechanisms, let’s turn to our final structural pattern. The Bridge pattern addresses a different challenge: separating an abstraction from its implementation so that both can evolve independently.

The Bridge pattern separates an abstraction from its implementation so that both can vary independently. In our calculator, we have two dimensions that might change: what we display (results, errors, expressions) and how we display it (console text, HTML, JSON). Without the Bridge pattern, these dimensions become entangled.

The challenge of multiple dimensions of variation

Section titled “The challenge of multiple dimensions of variation”

Consider a calculator display without the Bridge pattern. If we handle each combination directly, we get a combinatorial explosion:

fn show_result(value: f64, format: &str) {
match format {
"console" => println!("Result: {}", value),
"html" => println!(
"<div class=\"result\">{}</div>", value
),
"json" => println!(
"{{\"result\": {}}}", value
),
_ => panic!("Unknown format"),
}
}

This function handles one display operation for three formats. Adding show_error and show_expression triples the match arms. Adding a new format (say, CSV or XML) requires updating every display function. Adding a new display operation (like show_warning) requires adding a match arm to every format. The growth is multiplicative: M operations times N formats gives M × N match arms. The abstraction (what to display) and the implementation (how to format it) are locked together, creating fragile code that must change for two independent reasons.

The Bridge pattern decouples these dimensions by defining separate trait hierarchies for the abstraction and the implementation. The abstraction speaks in domain concepts (results, errors, expressions); the implementation speaks in output primitives (text, formatted values). Each dimension can be extended independently without affecting the other.

Designing the abstraction and implementation

Section titled “Designing the abstraction and implementation”

The abstraction defines what the display can do. The implementation defines how formatting works:

pub trait Display {
fn show_result(&self, result: f64);
fn show_error(&self, error: &str);
fn show_expression(
&self, expression: &dyn Expression,
);
}
pub trait DisplayImplementation {
fn display_text(&self, text: &str);
fn display_formatted(
&self, value: f64, format: &str,
);
}

The Display trait speaks in calculator concepts: results, errors, expressions. The DisplayImplementation trait speaks in formatting primitives: text and formatted values. The bridge connects them through composition:

pub struct CalculatorDisplay {
implementation: Box<dyn DisplayImplementation>,
}
impl CalculatorDisplay {
pub fn new(implementation: Box<dyn DisplayImplementation>) -> Self {
Self { implementation }
}
}
impl Display for CalculatorDisplay {
fn show_result(&self, result: f64) {
self.implementation
.display_formatted(result, "Result: {:.10g}");
}
fn show_error(&self, error: &str) {
self.implementation
.display_text(&format!("Error: {}", error));
}
fn show_expression(
&self, expression: &dyn Expression,
) {
self.implementation
.display_text(
&format!("Expression: {}",
expression.to_string())
);
}
}

The CalculatorDisplay struct translates high-level display operations into low-level formatting calls. It doesn’t know whether the output goes to a console, an HTML page, or a JSON API. That decision lives entirely in DisplayImplementation.

Each concrete implementation handles formatting for a specific output medium. The console implementation writes plain text:

pub struct ConsoleDisplay;
impl DisplayImplementation for ConsoleDisplay {
fn display_text(&self, text: &str) {
println!("{}", text);
}
fn display_formatted(
&self, value: f64, format: &str,
) {
println!("{}",
format.replace(
"{:.10g}", &format!("{:.10}", value)
)
);
}
}

The ConsoleDisplay struct writes plain text to standard output. It handles formatted values by replacing the format placeholder with the actual number, keeping the output simple and human-readable.

The HTML implementation wraps output in HTML elements:

pub struct HtmlDisplay;
impl DisplayImplementation for HtmlDisplay {
fn display_text(&self, text: &str) {
println!("<div>{}</div>",
text.replace("<", "&lt;")
.replace(">", "&gt;")
);
}
fn display_formatted(
&self, value: f64, format: &str,
) {
let formatted = format.replace(
"{:.10g}", &format!("{:.10}", value)
);
println!(
"<div class=\"result\">{}</div>", formatted
);
}
}

The HtmlDisplay struct wraps all output in <div> elements and escapes angle brackets in text to prevent HTML injection. The formatted result includes a CSS class for styling.

The JSON implementation produces machine-readable output:

pub struct JsonDisplay;
impl DisplayImplementation for JsonDisplay {
fn display_text(&self, text: &str) {
println!("{{\"text\": \"{}\"}}",
text.replace("\"", "\\\"")
);
}
fn display_formatted(
&self, value: f64, _format: &str,
) {
println!("{{\"result\": {:.10}}}", value);
}
}

JsonDisplay formats output as JSON, making it easy to use the output in other programs.

Adding a new output format requires only implementing display_text and display_formatted; no existing code needs to change. Adding a new display operation requires only modifying the Display trait and CalculatorDisplay. Neither change affects the other dimension.

The Bridge pattern applies beyond display formatting. Our calculator also separates evaluation abstraction from evaluation strategy:

pub trait EvaluationStrategy {
fn evaluate(
&self,
expression: &dyn Expression,
variables: &HashMap<String, f64>,
) -> Result<f64, String>;
}
pub struct StandardEvaluator;
impl EvaluationStrategy for StandardEvaluator {
fn evaluate(
&self,
expression: &dyn Expression,
variables: &HashMap<String, f64>,
) -> Result<f64, String> {
expression.evaluate(variables)
}
}

StandardEvaluator delegates directly to the expression’s own evaluation. An OptimizingEvaluator adds caching using interior mutability:

pub struct OptimizingEvaluator {
cache: RefCell<HashMap<String, f64>>,
}
impl EvaluationStrategy for OptimizingEvaluator {
fn evaluate(
&self,
expression: &dyn Expression,
variables: &HashMap<String, f64>,
) -> Result<f64, String> {
let expr_str = expression.to_string();
if let Some(&cached) = self.cache.borrow().get(&expr_str) {
return Ok(cached);
}
let result = expression.evaluate(variables)?;
self.cache.borrow_mut().insert(expr_str, result);
Ok(result)
}
}
pub struct Evaluator {
strategy: Box<dyn EvaluationStrategy>,
}
impl Evaluator {
pub fn new(strategy: Box<dyn EvaluationStrategy>) -> Self {
Self { strategy }
}
pub fn evaluate(
&self,
expression: &dyn Expression,
variables: &HashMap<String, f64>,
) -> Result<f64, String> {
self.strategy.evaluate(expression, variables)
}
pub fn change_strategy(&mut self,
strategy: Box<dyn EvaluationStrategy>,
) { self.strategy = strategy; }
}

The change_strategy method allows switching between standard and optimizing evaluation at runtime without creating a new Evaluator. This is particularly useful for scenarios where you want standard evaluation during development (for easier debugging) and optimizing evaluation in production. The caller controls the strategy; the Evaluator simply delegates.

The Bridge pattern is most valuable when you have two or more independent dimensions of variation. If your type hierarchy is growing in a grid-like pattern (each abstraction combined with each implementation), the Bridge can collapse that grid into two linear hierarchies.

In Rust, the Bridge pattern maps naturally to trait objects and composition. The abstraction holds a Box<dyn Implementation>, just as our CalculatorDisplay holds a Box<dyn DisplayImplementation>. When both dimensions are known at compile time and you want maximum performance, consider using generics instead of trait objects: struct CalculatorDisplay<I: DisplayImplementation> eliminates dynamic dispatch at the cost of monomorphization.

The Bridge pattern is closely related to the Strategy pattern (which we’ll explore in Chapter 7, Behavioral Patterns 1: Taking Action). Both use composition to delegate behavior to a trait object. The distinction is in intent: Bridge separates an abstraction’s interface from its implementation across two independent hierarchies, while Strategy provides interchangeable algorithms for a single behavior. Our evaluation bridge illustrates the overlap: the Evaluator struct holds a Box<dyn EvaluationStrategy> and delegates evaluation to it, which is structurally identical to Strategy. What makes it a Bridge as well is that we have two independent trait hierarchies (EvaluationStrategy for how to evaluate and the Expression tree for what to evaluate) that vary independently. When you encounter this kind of structural similarity in your own code, focus on the design intent rather than trying to classify the pattern definitively.

In this chapter, we explored different structural patterns and saw how Rust’s features shape their implementation.

We began with the Proxy pattern, discovering that Rust’s built-in mechanisms (LazyCell, smart pointers, module visibility) handle most proxy scenarios without custom code, giving us less boilerplate and stronger compile-time guarantees. The Decorator pattern showed us how to add cross-cutting concerns like logging, timing, caching, and range validation to expressions by wrapping them in layers that implement the same Expression trait. Each decorator is transparent to code that doesn’t need its added behavior, and decorators compose freely through stacking. The Adapter pattern demonstrated how to bridge incompatible interfaces, allowing our calculator to work with different scientific operation providers through a uniform ScientificOperations trait.

The Facade pattern gave us CalculatorFacade, a single struct that hides the complexity of parsers, variable stores, scientific operations, and history tracking behind a simple evaluate method. We also explored how Rust’s module system and pub use re-exports serve as a built-in facade mechanism at the crate level.

The Composite pattern provided the recursive Expression tree structure that makes our entire calculator possible. By having leaf nodes and composite nodes implement the same trait, we can represent and evaluate arbitrarily complex expressions through uniform recursive traversal.

We briefly examined the Flyweight pattern, finding that Rust’s const, static, Arc, and Cow provide built-in mechanisms for sharing data efficiently.

Finally, the Bridge pattern separated our display abstraction from its implementation, allowing us to add new output formats without modifying the display logic, and vice versa. A second bridge for evaluation strategies demonstrated the pattern’s versatility.

In the next chapter, we’ll shift from structural organization to behavioral patterns, exploring how the Command, Chain of Responsibility, Strategy, Mediator, and Template Method patterns can make our calculator interactive and responsive. Where structural patterns defined how our components connect, behavioral patterns will define how they communicate and react to user actions.