Skip to content
ImagineWorld

Structural Patterns in Rust

node_idnode-book_oop-to-rust_chapter-14-structural-patterns-in-rust
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num14
chapter_titleStructural Patterns in Rust
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 14 — Structural Patterns in Rust

Section titled “Chapter 14 — Structural Patterns in Rust”

Architecti sumus fortunae nostrae. (We are the architects of our own fortune.)

Creational patterns addressed how objects come into existence. Structural patterns address how objects compose into larger structures: how types connect, wrap, and organize to form coherent systems. The Gang of Four catalog includes Adapter, Bridge, Composite, Decorator, Facade, Flyweight, and Proxy. Each pattern organizes relationships between types to achieve flexibility, encapsulation, or interface compatibility.

The problems these patterns solve appear in every substantial codebase. External libraries expose interfaces that do not match application conventions. Complex subsystems need simplified entry points. Behavior must be added to objects without modifying their source. Tree structures must be traversed uniformly regardless of depth. Expensive operations must be deferred or cached. These are structural concerns: not how objects are created or how they behave, but how they relate to each other.

In object-oriented languages, structural patterns rely heavily on inheritance and interface implementation. A decorator inherits from the same base class as the component it decorates. A proxy implements the same interface as the object it represents. This inheritance-based approach enables polymorphism but creates coupling between the pattern implementation and the class hierarchy.

Rust’s approach differs fundamentally. Without inheritance, structural patterns rely on composition, traits, and the module system. The Adapter pattern wraps types to present different interfaces, using composition where OOP might use inheritance. Decorators compose behavior through trait implementations and delegation, with generics providing compile-time resolution. Facades use module visibility to hide complexity behind clean public APIs, leveraging Rust’s powerful privacy controls. Composites model recursive structures with enums and Box, pattern matching replacing polymorphic method dispatch. Proxies control access while maintaining interface compatibility through trait implementations.

The translations are often more explicit than their OOP counterparts, requiring more boilerplate for delegation but gaining clarity about what each layer does. In my experience, this explicitness makes the patterns easier to understand and maintain. When reading code, the structure is visible rather than hidden in inheritance hierarchies.

Adapter and wrapper types

The Adapter pattern converts one interface into another that clients expect. When a library provides a type with methods that do not match your application’s conventions, an adapter wraps that type and exposes the expected interface. The adapter delegates to the wrapped type, translating between interfaces.

The need for adapters arises constantly in real projects. A database driver returns results in one format while the application layer expects another. A third-party HTTP client uses different error types than the application’s error hierarchy. A legacy system uses string identifiers while new code uses typed IDs. Each mismatch requires translation, and adapters encapsulate that translation cleanly.

The alternative to adapters is scattered conversion code. Every call site that uses the mismatched interface must include translation logic. This scattering makes changes difficult: if the external interface changes, every call site must update. Adapters centralize the translation, isolating the rest of the codebase from interface details.

Consider integrating with an external logging library that uses a different method signature than your application expects. The external library uses severity levels as integers, while your application uses semantic methods like info, warn, and error. The external library might provide:

pub struct ExternalLogger {
prefix: String,
}
impl ExternalLogger {
pub fn new(prefix: &str) -> Self {
ExternalLogger { prefix: prefix.to_string() }
}
pub fn write_log(&self, severity: i32, msg: &str) {
println!("[{}] severity={}: {}", self.prefix, severity, msg);
}
}

Your application uses a different logging trait:

pub trait Logger {
fn info(&self, message: &str);
fn warn(&self, message: &str);
fn error(&self, message: &str);
}

An adapter bridges these interfaces:

pub struct LoggerAdapter {
inner: ExternalLogger,
}
impl LoggerAdapter {
pub fn new(inner: ExternalLogger) -> Self {
LoggerAdapter { inner }
}
}
impl Logger for LoggerAdapter {
fn info(&self, message: &str) {
self.inner.write_log(1, message);
}
fn warn(&self, message: &str) {
self.inner.write_log(2, message);
}
fn error(&self, message: &str) {
self.inner.write_log(3, message);
}
}

The adapter wraps ExternalLogger and implements Logger, translating method calls. The info method maps to severity 1, warn to severity 2, error to severity 3. The translation is centralized in the adapter; no other code needs to know about severity integers.

Client code works with the Logger trait, unaware of the underlying library. The rest of the application imports Logger and uses info, warn, error methods. Whether those methods ultimately call ExternalLogger, write to a file, send to a network service, or do nothing at all depends on which implementation is injected. The adapter enables this flexibility.

Swapping to a different logging implementation requires only a different adapter. If the application later switches from ExternalLogger to a different library with a different interface, only the adapter changes. All client code continues calling Logger methods unchanged. This isolation makes library upgrades and replacements much less disruptive.

This pattern is particularly common when integrating third-party crates. A database driver might expose one interface while your repository abstraction expects another. An HTTP client might use one error type while your application uses a unified error type. Adapters bridge these gaps without modifying either side.

The newtype pattern from the previous chapter is a specialized form of adapter. A newtype wraps a type to provide different trait implementations or method signatures. The distinction is subtle: newtypes typically add semantic meaning or type safety to an existing type, while adapters bridge incompatible interfaces. In practice, the implementation is identical.

Decorator via trait composition

The Decorator pattern attaches additional responsibilities to an object dynamically. Decorators wrap a component and add behavior before or after delegating to the wrapped component. Multiple decorators can stack, each adding its layer of functionality. Unlike subclassing, which adds behavior at compile time and affects all instances, decoration adds behavior to individual instances at runtime.

The classic motivation for decorators is cross-cutting concerns: logging, timing, caching, validation, retry logic. These concerns apply to many different operations but should not clutter each operation’s implementation. A method that sends a notification should focus on sending; adding logging should not require modifying the notification code.

In object-oriented languages, decorators inherit from the same base class as the component, overriding methods to add behavior and delegating to the wrapped instance. The decorator IS-A component (through inheritance) and HAS-A component (through composition). Rust achieves the same effect through traits and composition without inheritance. A decorator implements the same trait as the component it wraps, forwarding calls while adding behavior.

The pattern appears frequently in I/O operations. The standard library’s BufReader wraps a Read implementation, adding buffering without modifying the underlying reader. BufWriter does the same for Write. These are decorators: they implement the same traits as their wrapped types while adding functionality.

Consider a notification system where messages can be enhanced with various features. A notification might need logging, retry logic, rate limiting, or formatting. Each enhancement should be optional and combinable. The core trait defines what notifications do:

pub trait Notifier {
fn send(&self, message: &str);
}

A basic implementation sends messages directly. The EmailNotifier holds a recipient address and sends messages to that address. This is the concrete component that decorators will wrap. It implements the Notifier trait, establishing the interface that both component and decorators share.

Decorators wrap any Notifier and add behavior. A decorator holds an inner notifier (the thing it decorates) and implements the same trait. When its methods are called, the decorator performs its added behavior and then delegates to the inner notifier. This delegation

chains through any number of decorator layers, eventually reaching the concrete component.

The generic approach shown below uses type parameters (N: Notifier) for the inner notifier. This enables compile-time composition: the full type like RetryNotifier<LoggingNotifier<EmailNotifier>> is known at compile time, allowing the compiler to optimize away indirection. Each decorator wraps exactly one notifier type, which it knows statically:

pub struct LoggingNotifier<N: Notifier> {
inner: N,
}
impl<N: Notifier> LoggingNotifier<N> {
pub fn new(inner: N) -> Self {
LoggingNotifier { inner }
}
}
impl<N: Notifier> Notifier for LoggingNotifier<N> {
fn send(&self, message: &str) {
println!("LOG: Sending notification with message: {}", message);
self.inner.send(message);
}
}
pub struct RetryNotifier<N: Notifier> {
inner: N,
max_retries: u32,
}
impl<N: Notifier> RetryNotifier<N> {
pub fn new(inner: N, max_retries: u32) -> Self {
RetryNotifier { inner, max_retries }
}
}
impl<N: Notifier> Notifier for RetryNotifier<N> {
fn send(&self, message: &str) {
for attempt in 1..=self.max_retries {
println!("Attempt {} of {}", attempt, self.max_retries);
self.inner.send(message);
// In real code, check for success and break
}
}
}

Decorators compose by nesting. Creating a decorated notifier involves wrapping each layer around the previous. The construction reads inside-out: the innermost EmailNotifier is created first, then wrapped in LoggingNotifier, then that is wrapped in RetryNotifier. When the chain is called, execution flows outside-in: retry logic first, then logging, then the email send.

The construction pattern reflects typical error handling strategy. Retry wraps logging so that retries are logged. Logging wraps the actual operation so that the operation itself is logged. This order ensures that retry attempts appear in logs, and that successful operations (however many attempts they took) are recorded.

Each decorator adds its behavior and delegates to the wrapped notifier. The generic parameter N: Notifier allows decorators to wrap any notifier, including other decorators. The type system tracks the full decorator chain at compile time, enabling optimizations that runtime decoration cannot achieve.

This generic approach produces types like RetryNotifier<LoggingNotifier<EmailNotifier>>. The full chain is known at compile time, allowing the compiler to inline method calls through each layer. No virtual dispatch occurs; each layer’s send method is directly called. This static composition is more efficient than OOP’s typical decorator implementation using virtual methods.

The explicit type does have a cost: changing the decoration chain changes the type. If a function returns RetryNotifier<LoggingNotifier<EmailNotifier>>, adding a new decorator requires changing the return type. This rigidity suits configurations fixed at compile time but limits runtime flexibility.

For scenarios requiring runtime-configurable decoration, where the set of decorators is determined by configuration files or user input, trait objects provide the necessary flexibility:

pub struct DynamicNotifier {
inner: Box<dyn Notifier>,
}
impl DynamicNotifier {
pub fn new(inner: Box<dyn Notifier>) -> Self {
DynamicNotifier { inner }
}
pub fn with_logging(self) -> Box<dyn Notifier> {
Box::new(LoggingNotifier { inner: self })
}
}
impl Notifier for DynamicNotifier {
fn send(&self, message: &str) {
self.inner.send(message);
}
}

The trade-off is familiar: generics provide compile-time resolution and inlining, while trait objects enable runtime flexibility at the cost of dynamic dispatch.

Facade: module-level encapsulation

The Facade pattern provides a simplified interface to a complex subsystem. Rather than exposing dozens of types and their intricate interactions, a facade presents a cohesive API that handles common use cases. Clients interact with the facade; the subsystem’s complexity remains hidden.

Every substantial library faces a tension between power and usability. Internal components offer fine-grained control: separate loaders for each file format, individual filter functions, multiple encoding options. This granularity serves advanced users who need precise control. But most users want simple operations: load an image, apply some effects, save it. Exposing the full internal structure forces common cases to wade through complexity they do not need.

Facades resolve this tension by providing both levels. The facade handles common cases with simple APIs. Internal components remain available (perhaps through a separate module path) for advanced usage. Users start with the facade and dig deeper only when necessary.

Rust’s module system is particularly well-suited to facades. Visibility modifiers control what a module exposes: pub for public items, nothing for private. Re-exports using pub use compose public APIs from internal implementations. A well-designed module naturally becomes a facade, exposing a curated public interface while hiding implementation details.

Consider an image processing library with multiple internal components. Loading images requires format detection and format-specific decoders. Filters operate on raw pixel data. Saving requires format-specific encoders with various options. Orchestrating these components requires understanding their relationships:

// Internal module structure
mod image {
mod loader {
pub struct ImageLoader { /* ... */ }
impl ImageLoader {
pub fn load_png(path: &str) -> Result<RawImage, LoadError> { /* ... */ }
pub fn load_jpeg(path: &str) -> Result<RawImage, LoadError> { /* ... */ }
}
}
mod filters {
pub fn apply_blur(img: &mut RawImage, radius: f32) { /* ... */ }
pub fn apply_sharpen(img: &mut RawImage, amount: f32) { /* ... */ }
pub fn adjust_brightness(img: &mut RawImage, delta: i32) { /* ... */ }
}
mod encoder {
pub fn encode_png(img: &RawImage) -> Vec<u8> { /* ... */ }
pub fn encode_jpeg(img: &RawImage, quality: u8) -> Vec<u8> { /* ... */ }
}
pub struct RawImage { /* internal representation */ }
}

Without a facade, clients must understand loaders, filters, and encoders, managing the workflow themselves. Which loader handles which format? How do filters transform pixel data? What options does each encoder require? These questions burden every user of the library, even those who want simple operations.

A facade provides a streamlined interface that hides these details. The Image type presents a unified API: open, transform, save. Format detection happens automatically. Filter operations are exposed as simple methods. Encoding options use sensible defaults with optional customization. The facade makes common operations easy while the underlying components remain available for advanced use cases:

pub mod image {
use super::image::{loader, filters, encoder, RawImage};
pub struct Image {
raw: RawImage,
}
impl Image {
pub fn open(path: &str) -> Result<Self, ImageError> {
let raw = if path.ends_with(".png") {
loader::ImageLoader::load_png(path)?
} else if path.ends_with(".jpg") || path.ends_with(".jpeg") {
loader::ImageLoader::load_jpeg(path)?
} else {
return Err(ImageError::UnsupportedFormat);
};
Ok(Image { raw })
}
pub fn blur(&mut self, radius: f32) -> &mut Self {
filters::apply_blur(&mut self.raw, radius);
self
}
pub fn sharpen(&mut self, amount: f32) -> &mut Self {
filters::apply_sharpen(&mut self.raw, amount);
self
}
pub fn brightness(&mut self, delta: i32) -> &mut Self {
filters::adjust_brightness(&mut self.raw, delta);
self
}
pub fn save(&self, path: &str) -> Result<(), ImageError> {
let data = if path.ends_with(".png") {
encoder::encode_png(&self.raw)
} else {
encoder::encode_jpeg(&self.raw, 90)
};
std::fs::write(path, data)?;
Ok(())
}
}
}

Client code becomes straightforward. A single line opens an image, applies transformations, and saves the result. The chain of method calls reads like a description of the operation: open, blur, brighten, save. No mention of loaders, filters, or encoders. The complexity has been absorbed by the facade.

The facade determines file formats, selects appropriate loaders and encoders, and coordinates the subsystem. Each public method on Image maps to potentially complex internal operations. The open method detects file format and selects the appropriate loader. The filter methods apply transformations to internal pixel data. The save method selects an encoder based on the output path and writes the result.

This encapsulation enables evolution. If a new image format becomes popular, the facade can add support without changing its public interface. If a better filtering algorithm becomes available, the facade can adopt it transparently. Clients benefit from improvements without modification. The boundary between the facade and its clients becomes a stability contract. Clients need not know about ImageLoader, filter functions, or encoding details. The method chaining pattern (each method returning &mut Self) creates a fluent API that reads naturally.

Facades are not limited to hiding complexity. They also provide stability. Internal reorganization of the image processing modules does not affect clients using the facade. The public API remains constant while implementations evolve.

Composite with recursive types

The Composite pattern treats individual objects and compositions of objects uniformly. A file system is the classic example: files and directories share a common interface, but directories contain other entries, which may themselves be directories. The pattern enables tree structures where clients need not distinguish between leaves and branches.

Composites appear wherever hierarchical structures exist. Organization charts have employees who may manage other employees. UI layouts have containers holding other containers or widgets. Document structures have sections containing paragraphs or subsections. Mathematical expressions have operations containing other expressions. In each case, the same operations (display, calculate size, search) apply uniformly to both simple elements and complex compositions.

The alternative to composites is type-checking at every operation. Code must ask “is this a leaf or a container?” before proceeding differently. This checking spreads through the codebase, duplicating the same conditional logic. Composites centralize that logic: each type knows how to handle itself, and clients call methods without caring about the element’s nature.

Rust expresses composites using enums with recursive variants. An enum variant can contain the same enum type, creating the recursive structure. The compiler requires indirection through Box because it must know each type’s size at compile time, and a directly recursive type would have infinite size:

enum FileEntry {
File {
name: String,
size: u64,
},
Directory {
name: String,
entries: Vec<FileEntry>,
},
}
impl FileEntry {
pub fn name(&self) -> &str {
match self {
FileEntry::File { name, .. } => name,
FileEntry::Directory { name, .. } => name,
}
}
pub fn size(&self) -> u64 {
match self {
FileEntry::File { size, .. } => *size,
FileEntry::Directory { entries, .. } => {
entries.iter().map(|e| e.size()).sum()
}
}
}
pub fn print_tree(&self, indent: usize) {
let prefix = " ".repeat(indent);
match self {
FileEntry::File { name, size } => {
println!("{}{} ({} bytes)", prefix, name, size);
}
FileEntry::Directory { name, entries } => {
println!("{}{}/", prefix, name);
for entry in entries {
entry.print_tree(indent + 2);
}
}
}
}
}

The size method demonstrates the composite behavior: files return their own size, directories recursively sum their contents. Client code calls size() without knowing whether it addresses a file or a nested directory structure. This uniformity is the essence of the composite pattern. The caller does not need to check types or traverse manually; the composite handles its own complexity.

The print_tree method shows another common composite operation: traversal with context. The indent parameter accumulates as traversal descends into nested directories, producing visually nested output. Each level passes context to its children, creating coordinated behavior across the tree. Similar patterns appear in rendering UIs (accumulating transformations), evaluating expressions (accumulating variable bindings), or validating documents (accumulating path information).

Recursive operations on composites must be careful with deep structures. Each recursive call adds a stack frame. Extremely deep trees can overflow the stack. For unbounded depths, iterative approaches using explicit stacks or queues avoid this limit. The simple recursive approach shown here suffices for typical file system depths but may need adjustment for pathological cases.

Building composite structures can be done directly using struct literals, as shown below, or through builder patterns that provide more guided construction. The direct approach works well for tests and examples; production code often uses builders or parsers that construct the tree from external data:

let root = FileEntry::Directory {
name: "project".to_string(),
entries: vec![
FileEntry::File { name: "README.md".to_string(), size: 1024 },
FileEntry::Directory {
name: "src".to_string(),
entries: vec![
FileEntry::File { name: "main.rs".to_string(), size: 2048 },
FileEntry::File { name: "lib.rs".to_string(), size: 512 },
],
},
FileEntry::File { name: "Cargo.toml".to_string(), size: 256 },
],
};
println!("Total size: {} bytes", root.size());
root.print_tree(0);

The enum approach differs from the trait-based composite common in OOP. In OOP, both File and Directory implement a common interface, with Directory holding a collection of that interface type. Each type handles its own case, and polymorphism dispatches to the right implementation. In Rust, the enum bundles all variants together, and pattern matching handles each case. This centralizes behavior in methods rather than distributing it across implementations.

Both approaches have trade-offs. The OOP approach makes adding new operations difficult (every class needs a new method) but makes adding new types easy (define a new class implementing the interface). The enum approach makes adding new operations easy (add a new function with a match) but makes adding new types impossible without modifying the enum. This is the classic expression problem, and composites often favor stability of element types over stability of operations.

The enum approach provides additional safety through exhaustive matching. When a new variant is added to the enum, the compiler flags every match expression that does not handle it. This ensures that all operations account for all element types. The OOP approach offers no such guarantee; forgetting to implement a method in a new class produces a compile error, but there is no mechanism to ensure existing code handles the new class through polymorphic calls.

The following diagram shows the composite structure:

graph TD
    P["Directory: project"] --> R["File: README.md"]
    P --> S["Directory: src"]
    P --> C["File: Cargo.toml"]
    S --> M["File: main.rs"]
    S --> L["File: lib.rs"]

[!visual-conversion] A composite structure where directories contain files and other directories. Print tree diagram (PDF 379, printed p. 371) recreated in Mermaid; labels verbatim.

For composites requiring trait-based extensibility (where new variant types might be added by external code), a trait with Box<dyn Trait> collections provides that flexibility at the cost of the enum’s exhaustive matching guarantees.

Proxy patterns

The Proxy pattern provides a surrogate for another object to control access, add functionality, or defer expensive operations. The proxy and the real object share an interface; clients cannot distinguish between them. This transparency allows proxies to be inserted into existing code without modification.

Proxies differ from decorators in intent. Decorators add behavior: logging, caching, retry logic. Proxies control access: deferring creation, checking permissions, forwarding across networks. A decorator’s client usually knows decoration is happening (the behavior is the point). A proxy’s client typically should not know or care that a proxy exists; the proxy is transparent infrastructure.

Different proxy types serve different purposes. Virtual proxies defer object creation until the object is actually needed, useful when construction is expensive but may not be required. Protection proxies control access based on permissions, checking authorization before delegating to the real object. Remote proxies represent objects in different address spaces, hiding network communication behind local method calls. Caching proxies store results of expensive operations, returning cached values on subsequent calls.

Virtual proxies are particularly valuable for resource-intensive objects. Consider a document viewer where loading high-resolution images is costly. The document might reference hundreds of images, but only a few are visible at any time. Loading all images at startup wastes time and memory. A virtual proxy represents each image, deferring the actual load until the image needs to display:

pub trait Image {
fn display(&self);
fn dimensions(&self) -> (u32, u32);
}
pub struct RealImage {
path: String,
data: Vec<u8>,
width: u32,
height: u32,
}
impl RealImage {
pub fn load(path: &str) -> Self {
println!("Loading image from disk: {}", path);
// Expensive disk and decode operation
RealImage {
path: path.to_string(),
data: vec![0; 1024 * 1024], // Simulate loaded data
width: 1920,
height: 1080,
}
}
}
impl Image for RealImage {
fn display(&self) {
println!("Displaying image: {} ({}x{})", self.path, self.width, self.height);
}
fn dimensions(&self) -> (u32, u32) {
(self.width, self.height)
}
}

A lazy proxy defers loading until display is called:

use std::cell::OnceCell;
pub struct LazyImage {
path: String,
image: OnceCell<RealImage>,
}
impl LazyImage {
pub fn new(path: &str) -> Self {
println!("Creating proxy for: {}", path);
LazyImage {
path: path.to_string(),
image: OnceCell::new(),
}
}
fn get_or_load(&self) -> &RealImage {
self.image.get_or_init(|| RealImage::load(&self.path))
}
}
impl Image for LazyImage {
fn display(&self) {
self.get_or_load().display();
}
fn dimensions(&self) -> (u32, u32) {
self.get_or_load().dimensions()
}
}

The OnceCell ensures the image loads exactly once, on first access. Constructing a LazyImage is cheap; the expensive load happens only when needed. A document with many images loads quickly, deferring image loading until the user scrolls to each image.

The OnceCell type from the standard library is perfect for lazy initialization. It starts empty and can be initialized exactly once, then provides shared access to the contained value. The get_or_init method atomically checks whether the cell has a value and initializes it if not, returning a reference either way. This pattern avoids both the overhead of eager initialization and the complexity of manual “has it been loaded?” checks.

Protection proxies add access control. The real object has no concept of authorization; it performs its function when called. The proxy interposes between client and object, checking permissions before forwarding calls. This separation keeps authorization logic out of the object itself, allowing the same object to be accessed through different proxies with different permission policies:

pub struct ProtectedResource {
data: String,
}
impl ProtectedResource {
pub fn access(&self) -> &str {
&self.data
}
}
pub struct ProtectedProxy {
resource: ProtectedResource,
allowed_users: Vec<String>,
}
impl ProtectedProxy {
pub fn new(resource: ProtectedResource, allowed_users: Vec<String>) -> Self {
ProtectedProxy { resource, allowed_users }
}
pub fn access(&self, user: &str) -> Result<&str, AccessError> {
if self.allowed_users.contains(&user.to_string()) {
Ok(self.resource.access())
} else {
Err(AccessError::Unauthorized)
}
}
}

The proxy interposes access control before delegating to the real resource. The resource itself contains no authorization logic; the proxy layer handles that concern. This separation allows the same resource to be accessed with different permission rules in different contexts, or to change permission rules without modifying the resource implementation.

The protection proxy pattern proves particularly valuable in web applications. A service object performs business operations. Different proxies wrap it for different contexts: an admin proxy allows all operations, a user proxy restricts to owned resources, a guest proxy provides read-only access. The service remains simple and focused; authorization complexity lives in the proxy layer.

Caching proxies store results of expensive operations. Database queries, network requests, complex calculations: any operation that is expensive and produces consistent results for the same inputs benefits from caching. The proxy checks its cache before delegating, returning stored results when available:

use std::collections::HashMap;
use std::cell::RefCell;
pub trait DataFetcher {
fn fetch(&self, key: &str) -> Option<String>;
}
pub struct DatabaseFetcher;
impl DataFetcher for DatabaseFetcher {
fn fetch(&self, key: &str) -> Option<String> {
println!("Fetching {} from database", key);
// Expensive database query
Some(format!("data for {}", key))
}
}
pub struct CachingProxy<F: DataFetcher> {
fetcher: F,
cache: RefCell<HashMap<String, String>>,
}
impl<F: DataFetcher> CachingProxy<F> {
pub fn new(fetcher: F) -> Self {
CachingProxy {
fetcher,
cache: RefCell::new(HashMap::new()),
}
}
}
impl<F: DataFetcher> DataFetcher for CachingProxy<F> {
fn fetch(&self, key: &str) -> Option<String> {
if let Some(cached) = self.cache.borrow().get(key) {
println!("Cache hit for {}", key);
return Some(cached.clone());
}
if let Some(value) = self.fetcher.fetch(key) {
self.cache.borrow_mut().insert(key.to_string(), value.clone());
Some(value)
} else {
None
}
}
}

The caching proxy implements the same trait as the underlying fetcher, making it a transparent replacement. First access fetches from the database; subsequent accesses return cached values.

The RefCell enables interior mutability: the cache can be modified through a shared reference. This is necessary because the DataFetcher trait takes &self, not &mut self. The fetch method appears immutable from the trait’s perspective, but the caching proxy needs to update its internal cache. Interior mutability bridges this gap, though it moves borrow checking from compile time to runtime.

Caching introduces complexity around invalidation. When does cached data become stale? The simple proxy above caches forever, appropriate for immutable data. Real systems often need time-based expiration, explicit invalidation, or size limits. These concerns can be layered through additional proxies or integrated into a more sophisticated caching implementation.

Combining structural patterns

Real systems combine these patterns. An API client might use a facade to present a clean interface, adapters to normalize responses from different endpoints, decorators for logging and retry logic, and a caching proxy to avoid redundant requests. The patterns layer naturally because each addresses a specific concern without interfering with others.

The key to successful combination is clear separation of concerns. Each pattern handles one aspect: adapters handle interface translation, decorators handle behavior augmentation, proxies handle access control, facades handle complexity hiding. When responsibilities are clear, patterns compose without conflict. When responsibilities blur, the combination becomes a tangled mess.

Layering order often matters. Caching usually occurs outside retry logic: if a request succeeds, cache the result; if it fails, retry. Logging usually occurs outside everything: log the complete request including all decoration. Authentication usually occurs early: there is no point retrying or caching if the request will fail authorization. Understanding these dependencies guides how patterns stack.

Consider a weather service client that combines several patterns. The client needs to fetch weather data from an external API, but the raw API is complex and returns data in an inconvenient format. The client should retry failed requests, cache successful responses, and present a simple interface to application code:

// Facade over complex HTTP and parsing logic
pub struct WeatherService {
client: CachingProxy<RetryingFetcher<HttpClient>>,
}
impl WeatherService {
pub fn new() -> Self {
let http = HttpClient::new();
let with_retry = RetryingFetcher::new(http, 3);
let with_cache = CachingProxy::new(with_retry);
WeatherService { client: with_cache }
}
pub fn current_temperature(&self, city: &str) -> Result<f64, WeatherError> {
let response = self.client.fetch(&format!("/weather/{}", city))?;
let adapted = WeatherAdapter::parse(&response)?;
Ok(adapted.temperature)
}
}

The facade hides the layered infrastructure. Clients call current_temperature without knowing about retries, caching, or response adaptation. Each layer contributes its capability while maintaining a consistent interface.

This combination exemplifies how structural patterns compose. The adapter normalizes external data. The decorator adds retry resilience.

The proxy adds caching performance. The facade ties everything together with a clean API. Each pattern handles its concern; together they create a robust, efficient, and easy-to-use service.

The layering is not arbitrary. Caching wraps retry because we want to cache successful results, not retry attempts. Retry wraps the HTTP client because retry logic applies to network operations. The adapter transforms data after retrieval because the raw response needs normalization. Understanding why each layer exists and where it belongs is as important as knowing what it does.

Structures Explored

Structural patterns organize relationships between types to achieve interface compatibility, added behavior, simplified access, or recursive structures. Rust implements these patterns through composition and traits rather than inheritance, trading implicit behavior for explicit structure.

Adapters wrap types to present different interfaces, bridging incompatibilities between libraries and application code. The pattern centralizes translation logic, isolating the application from external interface changes. The newtype pattern is a specialized adapter that adds type safety or semantic meaning. Both patterns use the same mechanism: a wrapping type that exposes a different interface than its contents.

Decorators compose behavior through trait implementations that wrap other implementations. The pattern enables cross-cutting concerns like logging, timing, retry logic, and caching without modifying the core implementations. Generic decorators resolve at compile time, enabling inlining and optimization. Trait object decorators enable runtime configuration at the cost of dynamic dispatch. Both approaches stack naturally, with each layer adding its responsibility.

Facades use Rust’s module system to hide complexity behind clean public APIs. The pattern serves both simplicity and stability: simple APIs for common cases, stable boundaries that shield clients from internal changes. Visibility modifiers control what clients see, re-exports compose the public interface, and method chaining creates fluent APIs that read naturally.

Composites model recursive structures through enums with Box for indirection. The pattern enables uniform treatment of leaves and branches, with each element handling its own case through pattern matching. The compiler ensures exhaustive coverage, flagging any operation that fails to handle all element types.

Proxies control access, defer expensive operations, or cache results. Different proxy types serve different purposes: virtual proxies for lazy initialization, protection proxies for authorization, caching proxies for performance. They implement the same traits as the types they proxy, making substitution transparent to clients. The proxy intercepts calls, adds its concern, and delegates.

The patterns combine naturally because each addresses a distinct concern. A single subsystem might use facades for public API design, adapters for external integrations, decorators for cross-cutting concerns, and proxies for performance optimization. Understanding when each pattern applies, and how they compose, enables building systems that remain manageable as they grow.

The next chapter examines behavioral patterns, focusing on how objects interact and distribute responsibility. Strategy, Observer,

Command, and other patterns take different forms in Rust, often mplified by closures, channels, and the ownership model.