Skip to content
ImagineWorld

Creational Patterns: Making Things

node_idnode-book_design-patterns-and-best-practices-in-rust_chapter-05-creational-patterns-making-things
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num5
chapter_titleCreational Patterns: Making Things
pillar_membershipJ — architecture_design_craft
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 5 — Creational Patterns: Making Things

Section titled “Chapter 5 — Creational Patterns: Making Things”

In this chapter, we will explore how traditional creational design patterns translate to Rust, and how Rust’s unique features often provide better alternatives. We’ll examine which patterns need adapting and which might be unnecessary due to the language’s built-in features that serve the same purpose more effectively.

First, we’ll look at the Factory Method and how Rust’s functions-as-constructors convention (see the Rust API Guidelines, “Constructors are static inherent methods (C-CTOR)”: https://rust-lang.github.io/api-guidelines/predictability.html) provides a natural way to implement it. Then, we’ll explore when the Abstract Factory is helpful in Rust and when it’s not needed. In many cases, Rust’s trait system and generics can accomplish what the Abstract Factory does in object-oriented languages without the same complexity. We’ll see cases where simple trait bounds often suffice, and when the full pattern truly adds value. Next, we’ll discuss how the Builder pattern can be particularly effective in Rust. Finally, we’ll examine how Rust’s traits and standard library features often eliminate the need for patterns such as Singleton and Prototype.

We will also begin our new project: Correct Calculator. Unlike our previous “bad” calculator that demonstrated anti-patterns, this project will show how to build an application using idioms and patterns that work naturally with Rust. We’ll start with the foundational types and see how creational patterns can help us build a clean, maintainable code base.

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

  • Factory Method
  • Abstract Factory
  • Builder
  • Singleton
  • Prototype

In this section, we will explore how the Factory Method works in Rust. We’ll see how Rust’s approach to constructors and its powerful type system often provide alternatives that are more idiomatic than traditional Factory Method implementations.

In object-oriented languages, the Factory Method encapsulates object creation, hiding instantiation logic and often enabling subclass customization. This is typically achieved through inheritance and virtual methods. Rust doesn’t have classes or inheritance, so the pattern adapts: instead of virtual methods that subclasses override, Rust uses associated functions (methods without self) that return concrete types. The encapsulation benefit remains. Callers don’t need to know the construction details, but the polymorphism comes from enums and traits rather than inheritance hierarchies.

Let’s see how this manifests in our Correct Calculator project, where we need to create different kinds of tokens to represent numbers, operators, and functions in our expressions.

In an object-oriented language, we might create a Token class hierarchy with factory methods for each type. In Rust, we can take a more natural approach. Rather than creating a complex class hierarchy, we’ll use Rust’s enums (which provide sum type functionality) to represent our different token types. This approach leverages Rust’s pattern-matching capabilities and gives us type safety without inheritance. We’ll define our tokens as enum variants, with each variant holding the appropriate data for that token type. Then, we’ll add constructor methods that act as our factory methods, providing a clean API for creating tokens while encapsulating any validation logic that we need.

To begin with, we can define types for operators and functions using enums to represent the different variants. We’ll also create a Token enum that unifies all token types (number, operator, variable, and function):

#[derive(Debug, Clone, PartialEq)]
pub enum Token {
Number(f64),
Operator(Operator),
Function(Function),
Variable(String),
}

The Token enum is the heart of our expression representation, as it unifies different variants into a single type. Each variant represents a different element that can appear in a mathematical expression.

Note: Why Operator(Operator)?

The Operator(Operator) pattern may look redundant, but it’s idiomatic Rust where an enum variant wraps another enum. The outer Operator is the Token variant name; the inner is the wrapped Operator enum type.

Alternative approaches include renaming the variant (for example, Op(Operator)) or the type (for example, OperatorKind), but the repetition actually aids clarity; when you see Token::Operator(op), you immediately know that op is an Operator. This convention is used throughout the Rust ecosystem, including in popular crates such as syn for parsing Rust code.

Now let’s define the specific operators that our calculator will support:

#[derive(Debug, Clone, PartialEq)]
pub enum Operator {
Add,
Subtract,
Multiply,
Divide,
}

Each operator variant corresponds to a basic arithmetic operation. We derive Debug for printing during development, Clone for copying tokens when building expressions, and PartialEq for comparing tokens in tests and validation logic.

Finally, let’s define the mathematical functions:

#[derive(Debug, Clone, PartialEq)]
pub enum Function {
Sqrt,
Sin,
Cos,
Tan,
}

These function variants represent unary mathematical functions. In a more advanced calculator, we might add functions with multiple arguments, but for now, we’ll keep it simple with single-argument functions.

Now we can implement constructors for all of these different token types:

impl Token {
pub fn number(value: f64) -> Self {
Self::Number(value)
}
pub fn operator(op: Operator) -> Self {
Self::Operator(op)
}
pub fn function(func: Function) -> Self {
Self::Function(func)
}
pub fn variable(name: impl Into<String>) -> Self {
Self::Variable(name.into())
}
}

Here, the associated functions act as factory methods for creating number, operator, function, and variable tokens.

The variable method uses impl Into<String> as its parameter type. This is a common Rust idiom that accepts any type convertible to String, including &str, String, and other string-like types. Callers can write Token::variable("x") with a string literal or Token::variable(my_string) with an owned String, and the conversion happens automatically via the .into() call.

At the beginning of this section, we talked about how in traditional object-oriented languages, the Factory Method often involves complex class hierarchies. For our example, in Rust or C++, we might have the following:

  • An abstract Token base class with a virtual create() method
  • Concrete subclasses such as NumberToken and OperatorToken
  • A TokenFactory class with methods that return the base Token type
  • Runtime polymorphism to handle different token types

This approach requires inheritance and virtual dispatch, and often results in verbose boilerplate code.

In contrast, our Rust implementation is remarkably simple. These methods do not look like traditional factory methods. They simply look like constructors for enum variants. However, they provide exactly what we need from the Factory Method pattern. They encapsulate creation logic and provide a clear interface for creating tokens. They also hide implementation details and make the code more maintainable by centralizing creation logic.

The key difference is that Rust’s enum system gives us polymorphism through variants rather than inheritance, and pattern matching provides exhaustive handling at compile time rather than virtual dispatch at runtime. This makes our code both safer and more performant.

Let’s see how we might use these to build expressions. In Rust, collections such as Vec must contain elements of a single type. You can’t mix Operator, Function, and f64 in the same vector. The Token enum solves this by providing a unified type that can hold any token variant.

First, we’ll create a simple expression (2 + 3), then a more complex one (sin(x)):

let expr = vec![
Token::number(2.0),
Token::operator(Operator::Add),
Token::number(3.0),
];
let expr = vec![
Token::function(Function::Sin),
Token::variable("x"),
];

But what if we need more complex creation logic? For example, suppose we want to parse strings into tokens. We can extend our factory methods by parsing and matching on the string. We’ll try parsing as a number first, then see whether it’s an operator or a function. If it isn’t one of those, we’ll try to parse it as a variable. If that doesn’t work, we’ll return an error. Here’s how that could look:

impl Token {
// Previous methods...
pub fn from_str(s: &str) -> Result<Self, String> {
if let Ok(num) = s.parse::<f64>() {
return Ok(Self::number(num));
}
match s {
"+" => Ok(Self::operator(Operator::Add)),
"-" => Ok(Self::operator(Operator::Subtract)),
"*" => Ok(Self::operator(Operator::Multiply)),
"/" => Ok(Self::operator(Operator::Divide)),
"sin" => Ok(Self::function(Function::Sin)),
"cos" => Ok(Self::function(Function::Cos)),
"sqrt" => Ok(Self::function(Function::Sqrt)),
name if name.chars().all(|c| c.is_alphanumeric() || c == '_') =>
Ok(Self::variable(name)),
_ => Err(format!("Invalid token: {}", s)),
}
}
}

The from_str method implements our parsing strategy by trying each token type in order of specificity. First, it attempts to parse the input as a floating-point number using Rust’s built-in parse(). If that fails, it matches against known operators and function names. Variable names are validated last, accepting any alphanumeric string with underscores. This cascading approach ensures that numeric strings such as “123” aren’t accidentally treated as variable names, while still allowing flexibility for user-defined variables.

Now we can create tokens from strings (such as our simple expression, 2 + 3), with proper error handling:

let tokens: Result<Vec<_>, _> = "2 + 3"
.split_whitespace()
.map(Token::from_str)
.collect();
match tokens {
Ok(expr) => println!("Valid expression: {:?}", expr),
Err(e) => println!("Error: {}", e),
}

This example shows our factory method handling a complete expression. The split_whitespace() iterator breaks the input into tokens, and map(Token::from_str) applies our factory method to each piece. The collect() call gathers the results, and because each from_str returns a Result, the entire collection becomes Result<Vec<_>, _>. If any token fails to parse, the error propagates automatically.

Note: Using String as the error type in Result

In production code, you’d typically define a dedicated error type (such as TokenError) rather than returning String. This enables pattern matching on specific error kinds and integrates better with Rust’s error-handling ecosystem. We use String here for simplicity, but Chapter 9, Architectural Patterns, will demonstrate proper error type design.

In many languages, factories are a pattern that we impose upon the language. For Rust, factories are the idiomatic and natural way to create type instances.

Our basic factory methods work well for creating individual tokens, but real calculators need to handle more complex scenarios. For example, we might want to create special operators that combine multiple tokens or handle different numeric formats. Let’s extend our factories to handle these cases.

First, we should define the data types that we will need:

#[derive(Debug, Clone, PartialEq)]
pub enum Token {
Number(Number), // Now using a dedicated Number type
Operator(Operator),
Function(Function),
Variable(String),
}
#[derive(Debug, Clone, PartialEq)]
pub struct Number {
value: f64,
format: NumberFormat,
}
#[derive(Debug, Clone, PartialEq)]
pub enum NumberFormat {
Decimal,
Scientific,
Engineering,
// More formats can be added...
}

We introduce the Number struct to track not just the numeric value but also how it should be displayed. The NumberFormat enum captures the user’s input format, whether they typed 123.45 (decimal) or 1.23e-4 (scientific) or entered a value that should display in engineering notation. This separation allows our calculator to preserve the user’s preferred notation throughout calculations, rather than converting everything to a single format.

Then, we need to build the different functions to create tokens from the different number formats. They must detect the number format and automatically create the correct variant. For example, the factories will need to recognize scientific notation such as 1.23E-4, as well as decimal notation:

impl Token {
pub fn number_from_str(s: &str) -> Result<Self, String> {
if s.contains('e') || s.contains('E') {
Self::scientific_number(s)
} else {
Self::decimal_number(s)
}
}
fn scientific_number(s: &str) -> Result<Self, String> {
s.parse::<f64>()
.map(|v| Self::Number(Number {
value: v,
format: NumberFormat::Scientific,
}))
.map_err(|_| format!("Invalid number: {}", s))
}
fn decimal_number(s: &str) -> Result<Self, String> {
s.parse::<f64>()
.map(|v| Self::Number(Number {
value: v,
format: NumberFormat::Decimal,
}))
.map_err(|_| format!("Invalid decimal number: {}", s))
}
}

You might notice that scientific_number and decimal_number have nearly identical implementations. Only the NumberFormat tag differs. This redundancy is intentional for clarity; each function explicitly shows what format it creates. In production code, you could refactor this into a single helper:

fn parse_number(s: &str, format: NumberFormat) -> Result<Token, String> {
s.parse::<f64>()
.map(|v| Token::Number(Number { value: v, format }))
.map_err(|_| format!("Invalid number: {}", s))
}

For the purposes of this chapter, we’ll keep the separate functions here to make the Factory Method pattern’s structure explicit.

Now we need to implement the format method for the Number struct. Each format knows how to display itself, and we encapsulate that logic in one place:

impl Number {
pub fn format(&self) -> String {
match self.format {
NumberFormat::Decimal => format!("{}", self.value),
NumberFormat::Scientific => format!("{:e}", self.value),
NumberFormat::Engineering => {
// Engineering notation adjusts exponent to be multiple of 3
let exp = self.value.abs().log10().floor();
let adj_exp = (exp - exp % 3.0).floor();
let coeff = self.value / 10_f64.powf(adj_exp);
format!("{}e{}", coeff, adj_exp)
}
}
}
}

The format method is where the real power of our Number struct becomes clear. Each number format has its own display logic, including Decimal format (standard notation such as 123.45), Scientific format (exponential notation such as 1.23e-4, which is useful for very large or small numbers), and Engineering format (a variant of scientific notation where the exponent is always a multiple of 3, matching common SI prefixes such as kilo- or mega-).

An alternative approach would be to define a Formattable trait with separate implementations for each format. That’s more extensible. New formats could be added without modifying this function. However, the match-based approach keeps all formatting logic visible in one place, which aids understanding. For our calculator’s fixed set of formats, this trade-off favors simplicity.

The engineering format calculation deserves special attention. It adjusts the exponent to be a multiple of 3, which makes numbers easier to read in engineering contexts. For example, instead of 1.2e5 (scientific), we get 120e3 (engineering), which clearly represents 120,000.

Now we can create numbers with appropriate formatting:

let numbers = [
"123.45", // Decimal
"1.23e-4", // Scientific
"1200000", // Could be formatted as engineering
];
for num_str in numbers {
match Token::number_from_str(num_str) {
Ok(Token::Number(num)) => println!("{} -> {}", num_str, num.format()),
Err(e) => println!("Error: {}", e),
_ => unreachable!(),
}
}

This loop demonstrates our number factory in action. Each string is parsed by number_from_str, which automatically detects the format and creates an appropriately tagged Number. When we call format() on the result, the number displays in its original notation. The pattern match ensures we only process successful parses, while errors are reported with context about what went wrong.

We can also add support for compound operators, that is, operators that are made up of multiple characters but represent a single operation:

#[derive(Debug, Clone, PartialEq)]
pub enum Operator {
// Basic operators
Add,
Subtract,
Multiply,
Divide,
// Compound operators
Power,
Root,
Factorial,
}
impl Token {
pub fn operator_from_str(s: &str) -> Result<Self, String> {
let op = match s {
// Basic operators
"+" => Operator::Add,
"-" => Operator::Subtract,
"*" => Operator::Multiply,
"/" => Operator::Divide,
// Compound operators
"**" | "^" => Operator::Power,
"//" => Operator::Root,
"!=" => Operator::Factorial,
_ => return Err(format!("Unknown operator: {}", s)),
};
Ok(Self::Operator(op))
}
}

The operator_from_str method maps string representations to our Operator enum variants. Single-character operators such as + and - get their own arms, while compound operators such as ** (power) and ^ (also power) can share the same variant. The // operator for the nth root demonstrates that we can support multi-character operators naturally. Unknown operators return an error with the invalid string, helping users identify typos.

Next, we will need to convert the input text into a stream of tokens. To do this, we can create a token parser that will read the input and iterate through the tokens that it finds. We’ll need to be certain that it also handles multi-character operators.

We can start by defining the TokenParser struct itself:

pub struct TokenParser {
input: String,
position: usize,
}
impl TokenParser {
pub fn new(input: impl Into<String>) -> Self {
Self {
input: input.into(),
position: 0,
}
}
}

TokenParser works by maintaining a position cursor in the input string. In the constructor, we store the input as an owned string, then start the cursor at the beginning.

Now we can implement the core parsing logic in the next_token method:

impl TokenParser {
pub fn next_token(&mut self) -> Option<Result<Token, String>> {
self.skip_whitespace();
if self.position >= self.input.len() {
return None;
}
let remaining = &self.input[self.position..];
if let Some(len) = self.match_operator(remaining) {
let op_str = &remaining[..len];
self.position += len;
return Some(Token::operator_from_str(op_str));
}
Some(Err("Incomplete implementation".to_string()))
}
}

The next_token method first skips any whitespace, then examines the remaining input to determine what kind of token comes next.

To support this logic, we define a few helper methods:

impl TokenParser {
fn match_operator(&self, s: &str) -> Option<usize> {
let operators = ["**", "///", "+", "-", "*", "/", "!="];
operators.iter()
.filter(|op| s.starts_with(*op))
.map(|op| op.len())
.next()
}
fn skip_whitespace(&mut self) {
while self.position < self.input.len() &&
self.input[self.position..].starts_with(char::is_whitespace) {
self.position += 1;
}
}
}

For operators, next_token uses match_operator to find the longest matching operator string. This is why compound operators such as ** are listed before * in the operators array. The parser returns None when the input is exhausted, making it suitable for use in iterator-like loops.

This more advanced factory system gives us several advantages. First, numbers maintain their original format for display. Also, complex operators are handled cleanly. The token creation logic is encapsulated but extensible, and error handling is consistent throughout.

However, there are some limitations to this approach. All tokens are created through the same set of factory methods, which means we can’t easily swap out entire families of related tokens. For instance, what if we want a scientific calculator mode that uses completely different number formats and operators? Or a programmer’s calculator that works with hexadecimal and bitwise operations? With our current approach, we’d need to add more complexity to our single Token type and its factory methods.

This is where Abstract Factory can be valuable. It allows us to create families of related objects that work together, ensuring that we don’t accidentally mix incompatible token types from different calculator modes.

In the next section, we’ll look at the Abstract Factory and how it can help us manage different variants of our calculator’s functionality.

In this section, we’ll explore Abstract Factory in Rust. The traditional Abstract Factory pattern creates families of related objects, ensuring they work together correctly. In Rust, we’ll see how this concept often maps more naturally to traits and associated types.

In our calculator, we might want to support different modes of operation, for example, standard arithmetic mode, scientific mode, or programming mode (with hex/binary numbers and bitwise operations). Each mode needs its own set of tokens, operators, and evaluation rules.

Let’s see how we might approach this. First, we will need to define some traits for our different token types. For the Abstract Factory pattern, we’ll use Rust’s trait system to define interfaces for our token types.

Unlike object-oriented languages, where we’d create abstract base classes, Rust’s traits provide a more flexible way to define shared behavior. We’ll create traits that specify what operations numbers and operators must support, then implement these traits for different calculator modes.

Traits combined with associated types allow us to ensure that all tokens from a given factory work together correctly. This gives us compile-time guarantees that we can’t mix incompatible token types.

Let’s define traits to describe the required behavior for numbers and operators:

pub trait NumberToken {
fn value(&self) -> f64;
fn format(&self) -> String;
}
pub trait OperatorToken {
fn precedence(&self) -> u8;
fn evaluate(&self, args: &[f64]) -> Result<f64, String>;
}

The NumberToken trait defines the interface for all number types across different calculator modes. The value() method returns the numeric value as a standard f64, while format() returns a string representation appropriate for that mode’s display conventions.

The OperatorToken trait is more complex. The precedence() method returns a priority value used during expression evaluation. Higher values mean the operator should be evaluated first. The evaluate() method performs the actual calculation, taking a slice of arguments and returning either a result or an error message for cases such as division by zero.

Now we define the TokenFactory trait, which ties everything together. Each calculator mode will implement this trait, specifying its own Number and Operator types through associated types. This ensures that tokens created by a factory are always compatible; you can’t accidentally mix ScientificNumber with StandardOperator:

pub trait TokenFactory {
type Number: NumberToken;
type Operator: OperatorToken;
fn create_number(&self, s: &str) -> Result<Self::Number, String>;
fn create_operator(&self, s: &str) -> Result<Self::Operator, String>;
}

The associated Number and Operator types are the key to type safety. When we write F::Number in generic code, the compiler knows exactly which number type we’re working with based on the factory. The trait methods return these associated types, guaranteeing that all tokens from a given factory work together correctly.

Let’s try implementing the standard arithmetic mode. We can start by creating a StandardNumber type and implementing our NumberToken trait for it:

pub struct StandardNumber(f64);
impl NumberToken for StandardNumber {
fn value(&self) -> f64 {
self.0
}
fn format(&self) -> String {
format!("{}", self.0)
}
}

StandardNumber is a simple wrapper around an f64 value. This NewType pattern is common in Rust, which we will discuss in Chapter 10, Patterns That Leverage the Type System. It creates a distinct type that implements our NumberToken trait. The implementation is straightforward: value() returns the wrapped number, and format() uses Rust’s standard floating-point formatting.

We can similarly create a StandardOperator type and implement OperatorToken:

pub struct StandardOperator(Operator);
impl OperatorToken for StandardOperator {
fn precedence(&self) -> u8 {
match self.0 {
Operator::Add | Operator::Subtract => 1,
Operator::Multiply | Operator::Divide => 2,
Operator::Power => 3,
Operator::Root | Operator::Factorial => 4,
}
}
fn evaluate(&self, args: &[f64]) -> Result<f64, String> {
match self.0 {
Operator::Add => Ok(args[0] + args[1]),
Operator::Subtract => Ok(args[0] - args[1]),
Operator::Multiply => Ok(args[0] * args[1]),
Operator::Divide => {
if args[1] == 0.0 {
Err("Division by zero".to_string())
} else {
Ok(args[0] / args[1])
}
}
// ... other operators
_ => Err("Operation not supported in standard mode".to_string()),
}
}
}

The StandardOperator implementation defines how basic arithmetic works in our calculator. The precedence method returns priority values that determine evaluation order. Multiplication and division (precedence 2) bind tighter than addition and subtraction (precedence 1). The evaluate method performs the actual computation, with special handling for division by zero. Unsupported operations in standard mode return an error, allowing scientific mode to provide extended functionality.

Then we can tie it all together with a factory. We’ll create a new StandardFactory type, and then implement TokenFactory on it:

pub struct StandardFactory;
impl TokenFactory for StandardFactory {
type Number = StandardNumber;
type Operator = StandardOperator;
fn create_number(&self, s: &str) -> Result<Self::Number, String> {
s.parse::<f64>()
.map(StandardNumber)
.map_err(|_| format!("Invalid number: {}", s))
}
fn create_operator(&self, s: &str) -> Result<Self::Operator, String> {
match s {
"+" => Ok(StandardOperator(Operator::Add)),
"-" => Ok(StandardOperator(Operator::Subtract)),
"*" => Ok(StandardOperator(Operator::Multiply)),
"/" => Ok(StandardOperator(Operator::Divide)),
_ => Err(format!("Invalid operator: {}", s)),
}
}
}

The ScientificNumber struct demonstrates how different factory families can have different internal representations. Unlike StandardNumber, which wraps a simple f64, ScientificNumber tracks the display format separately. This allows the scientific calculator to preserve whether a user entered 1.23e-4 versus 0.000123, displaying results in the same notation that they used for input.

Then we can also build a factory for the scientific calculator:

pub struct ScientificFactory;
impl TokenFactory for ScientificFactory {
type Number = ScientificNumber;
type Operator = ScientificOperator;
fn create_number(&self, s: &str) -> Result<Self::Number, String> {
// Handle both scientific and standard notation
if s.contains('e') || s.contains('E') {
s.parse::<f64>().map(|value| ScientificNumber {
value,
format: NumberFormat::Scientific,
})
} else {
s.parse::<f64>().map(|value| ScientificNumber {
value,
format: NumberFormat::Decimal,
})
}.map_err(|_| format!("Invalid number: {}", s))
}
fn create_operator(&self, s: &str) -> Result<Self::Operator, String> {
// Scientific mode supports more operators
match s {
"sin" => Ok(ScientificOperator::Function(Function::Sin)),
"cos" => Ok(ScientificOperator::Function(Function::Cos)),
// ... other scientific operators
_ => Err(format!("Invalid operator: {}", s)),
}
}
}

ScientificFactory shows how Abstract Factory enables mode-specific behavior. Its create_number method detects scientific notation (the presence of e or E) and tags numbers appropriately. Its create_operator method recognizes function names such as sin and cos that aren’t available in standard mode. This separation ensures that scientific features are only available when using the scientific factory.

Now we can create a calculator that works with any token factory:

struct Calculator<F: TokenFactory> {
factory: F,
expression: Vec<Token<F::Number, F::Operator>>,
}
impl<F: TokenFactory> Calculator<F> {
pub fn new(factory: F) -> Self {
Self {
factory,
expression: Vec::new(),
}
}
pub fn parse(&mut self, input: &str) -> Result<(), String> {
for token in input.split_whitespace() {
// Try operator first
if let Ok(op) = self.factory.create_operator(token) {
self.expression.push(Token::Operator(op));
continue;
}
// Must be a number then
let num = self.factory.create_number(token)?;
self.expression.push(Token::Number(num));
}
Ok(())
}
}
let standard_calc = Calculator::new(StandardFactory);
let scientific_calc = Calculator::new(ScientificFactory);

This approach gives us several advantages. Each calculator mode is self-contained, and Token types are guaranteed to work together. We can add new modes without modifying existing code, while the type system ensures we don’t mix incompatible tokens.

Notice how Rust’s type system, particularly traits and associated types, provides a natural way to express the Abstract Factory pattern. Instead of the complex inheritance hierarchies often seen in object-oriented languages, we get a clean, type-safe solution.

While Abstract Factory is powerful, it’s often unnecessary in Rust. Consider simpler alternatives first.

Use plain traits and generics in the following cases:

  • You only need polymorphism over a single type, not a family of related types
  • The “family” relationship isn’t important for correctness
  • You want to avoid the complexity of associated types

For example, if your calculator only needs different number formats but operators stay the same, use this:

// Simpler: just parameterize by number type
struct Calculator<N: NumberToken> {
// ...
}

Use Abstract Factory in the following cases:

  • You have multiple related types that must stay consistent (for example, ScientificNumber must pair with ScientificOperator)
  • Mixing types from different families would cause bugs
  • You need to swap entire families at runtime or compile time

The Abstract Factory pattern adds complexity. Only use it when that complexity buys you meaningful safety guarantees.

In the next section, we’ll look at the Builder pattern and how it can help us construct complex expressions more elegantly.

In this section, we’ll examine the operation of the Builder pattern in Rust. Although Builder is a pattern used in many languages, in Rust, it is especially useful because of the ownership model and type system. We’ll examine how builders can assist us in creating intricate expressions in a straightforward and secure manner.

We’re working with expressions in our calculator that can get rather complicated. They could include functions with several arguments, parentheses, several terms, and more. Directly creating these expressions could be challenging to read and prone to errors.

The Builder pattern solves this by separating the construction process into discrete steps. Each step adds one element to the expression and returns the builder itself, allowing us to chain method calls. This approach gives us compile-time safety for the construction process while making the code readable and maintainable.

Let’s see how a builder can assist by first defining our core structures:

pub struct Expression<F: TokenFactory> {
tokens: Vec<Token<F::Number, F::Operator>>,
factory: F,
}
pub struct ExpressionBuilder<F: TokenFactory> {
tokens: Vec<Token<F::Number, F::Operator>>,
factory: F,
paren_count: i32, // Track parentheses balance
}

The Expression struct represents our final, immutable expression, while ExpressionBuilder manages the construction process. Note how the builder tracks parentheses balance to ensure expressions are well formed.

The code repository uses a simpler, non-generic builder whose methods accept typed values directly (such as f64 and Operator). The version shown here accepts strings and parses them through the factory, which demonstrates how the Builder and Abstract Factory patterns compose: the builder delegates token creation to whichever factory it was given. The trade-off is that string parsing can fail, so our builder methods return Result.

Next, let’s implement the builder’s constructor and basic token-adding methods:

impl<F: TokenFactory> ExpressionBuilder<F> {
pub fn new(factory: F) -> Self {
Self {
tokens: Vec::new(),
factory,
paren_count: 0,
}
}
// Add a number to the expression
pub fn number(mut self, value: &str) -> Result<Self, String> {
let num = self.factory.create_number(value)?;
self.tokens.push(Token::Number(num));
Ok(self)
}
// Add an operator
pub fn operator(mut self, op: &str) -> Result<Self, String> {
let op = self.factory.create_operator(op)?;
self.tokens.push(Token::Operator(op));
Ok(self)
}
// Add a variable
pub fn variable(mut self, name: &str) -> Self {
self.tokens.push(Token::Variable(name.to_string()));
self
}
}

Each method takes ownership of self (note the mut self parameter) and returns it after modification. This ownership pattern enables method chaining while preventing accidental reuse of partially built expressions.

For handling parentheses, we need to take special care to maintain balance:

impl<F: TokenFactory> ExpressionBuilder<F> {
// Open a parenthesis group
pub fn open_paren(mut self) -> Self {
self.tokens.push(Token::OpenParen);
self.paren_count += 1;
self
}
// Close a parenthesis group
pub fn close_paren(mut self) -> Result<Self, String> {
if self.paren_count <= 0 {
return Err("Unmatched closing parenthesis".to_string());
}
self.tokens.push(Token::CloseParen);
self.paren_count -= 1;
Ok(self)
}
}

The close_paren method returns a Result because it can fail if there’s no matching opening parenthesis. This immediate error detection prevents invalid expressions from being built.

Finally, the build method performs final validation and creates the immutable Expression:

impl<F: TokenFactory> ExpressionBuilder<F> {
// Build the final expression
pub fn build(self) -> Result<Expression<F>, String> {
if self.paren_count != 0 {
return Err("Unmatched parentheses".to_string());
}
if self.tokens.is_empty() {
return Err("Empty expression".to_string());
}
// Validate the expression structure
self.validate_expression()?;
Ok(Expression {
tokens: self.tokens,
factory: self.factory,
})
}
fn validate_expression(&self) -> Result<(), String> {
// No consecutive operators
for window in self.tokens.windows(2) {
match (&window[0], &window[1]) {
(Token::Operator(_), Token::Operator(_)) => {
return Err("Consecutive operators".to_string());
}
_ => continue,
}
}
// More validation rules...
Ok(())
}
}

The validate_expression method checks that our token sequence forms a valid mathematical expression. The windows(2) call examines each pair of adjacent tokens, catching errors such as consecutive operators (2 + 3) that would make the expression unparsable. Additional validation rules (not shown) might check that the expression starts with a number or open parenthesis, ends with a number or close parenthesis, and has the right number of operands for each operator.

The build method consumes the builder (taking self by value), ensuring no further modifications can be made after building. It performs comprehensive validation, including parentheses matching and expression structure checks.

To provide a convenient entry point, we add a builder method to the Expression type itself:

// Make the Expression itself immutable and safe
impl<F: TokenFactory> Expression<F> {
pub fn builder(factory: F) -> ExpressionBuilder<F> {
ExpressionBuilder::new(factory)
}
pub fn evaluate(&self) -> Result<F::Number, String> {
// Evaluation logic here...
todo!()
}
}

Defining builder on Expression rather than calling ExpressionBuilder::new directly follows Rust convention: the type you’re building provides the entry point to its builder. This makes the API discoverable. Users typing Expression:: in their IDE see builder as an option. It also establishes a clear relationship: expressions are built by expression builders, and you start the process from the expression type itself.

Now we can build expressions with a fluent interface that helps prevent errors. A fluent interface is a method of designing APIs where method calls can be chained together, with each method returning an object (usually) that allows the next method call. This creates code that reads almost like natural language, making it more intuitive and self-documenting:

let expr = Expression::builder(StandardFactory)
.number("2")?
.operator("+")?
.open_paren()
.number("3")?
.operator("*")?
.number("4")?
.close_paren()?
.build()?;
// With scientific calculator
let expr = Expression::builder(ScientificFactory)
.number("1.23e-4")?
.operator("sin")?
.build()?;

The Builder pattern gives us several advantages here. Our expressions are constructed step by step in a very readable way, which will make the code much easier to understand. Additionally, invalid expressions are caught at build time, and each step returns a result, making error handling natural.

For very complex expressions, this fluent style can become unwieldy. In practice, large expressions are typically constructed by doing the following:

  • Parsing from strings: Instead of calling .number("2").operator("+")..., parse an expression such as "2 + (3 * 4)" directly (we’ll implement a parser later)
  • Composing subexpressions: Build smaller pieces separately, then combine them using helper methods such as binary_op or extend
  • Generating programmatically: Use loops or recursion to build expressions from data structures

The fluent builder excels for moderate-sized expressions where readability matters. For expression trees with dozens of nodes, string parsing or programmatic generation is more practical.

Specialized builders are builder methods that construct common expression patterns in a single call, such as binary_op("2", "+", "3"), instead of separate number, operator, and number calls. Creating specialized builders provides several advantages. First, they encapsulate common patterns, reducing code duplication across your code base. Instead of manually constructing the same expression structures repeatedly, you can use a single method call. Second, they improve readability by giving meaningful names to complex constructions. binary_op is much clearer than a chained series of calls. Third, they ensure consistency by centralizing the logic for building specific patterns, reducing the chance of errors. Finally, they make refactoring easier. If you need to change how binary operations are structured, you only need to update one method.

We can create specialized builder methods for common expression patterns, such as binary operations (two operands with an operator between them) and function applications (a function name followed by its argument):

impl<F: TokenFactory> ExpressionBuilder<F> {
pub fn function(mut self, func: &str, arg: &str) -> Result<Self, String> {
let func_op = self.factory.create_operator(func)?;
let arg_num = self.factory.create_number(arg)?;
self.tokens.push(Token::Operator(func_op));
self.tokens.push(Token::Number(arg_num));
Ok(self)
}
pub fn binary_op(
mut self,
left: &str,
op: &str,
right: &str
) -> Result<Self, String> {
let left_num = self.factory.create_number(left)?;
let op_token = self.factory.create_operator(op)?;
let right_num = self.factory.create_number(right)?;
self.tokens.extend([
Token::Number(left_num),
Token::Operator(op_token),
Token::Number(right_num),
]);
Ok(self)
}
}

These specialized methods encapsulate common expression patterns. The function method creates a function-application pattern (such as sin(0.5)) by adding the function operator followed by its argument. The binary_op method creates a complete binary operation (2 + 3) in a single call. Both methods handle token creation through the factory, ensuring type safety, and return Result to propagate any parsing errors. Using these methods instead of manual number/operator calls reduces boilerplate and makes the code’s intent clearer.

Now we can write our expressions even more concisely using our expression builder:

let expr = Expression::builder(StandardFactory)
.binary_op("2", "+", "3")?
.build()?;
let expr = Expression::builder(ScientificFactory)
.function("sin", "0.5")?
.build()?;

Notice how binary_op("2", "+", "3") replaces what would otherwise be three separate calls: .number("2")?.operator("+")?.number("3")?. The specialized method is not only more concise but also more intention-revealing. It’s immediately clear that we’re building a binary operation. Similarly, function("sin", "0.5") clearly expresses “apply sine to 0.5” without the reader needing to understand the underlying token structure.

The Builder pattern works particularly well in Rust for a variety of reasons. We have the Rust type system to ensure that the builder is being used correctly, and Result types provide clean error handling. We can leverage the ownership model for our method chaining to make it safe and fluent. Rust allows us to build immutable expressions safely.

The Builder pattern adds overhead for simple types. If your struct has only a few required fields and no complex validation, a simple constructor or struct literal is clearer:

// Overkill for simple types
let config = ConfigBuilder::new()
.precision(10)
.build();
// Better for simple types
let config = CalculatorConfig { precision: 10, ..Default::default() };

Reserve builders for types with many optional fields, complex validation rules, or step-by-step construction requirements.

In the next section, we’ll look at Singleton and why it’s often unnecessary in Rust.

In this section, we’ll explore the Singleton pattern and its place (or lack thereof) in Rust. While Singleton is a common pattern in many languages, Rust’s module system and type system often provide better alternatives. We’ll see why Singleton is rarely the best solution in Rust, and what to use instead.

The Singleton pattern is traditionally used to ensure that a class has only one instance, and it provides global access to that instance. Common use cases include configuration management, shared resources, and global state. Let’s see how this might appear in our calculator project.

Suppose we want to manage calculator settings globally. We can follow a traditional Singleton approach that we might use in an object-oriented language, which could look something like this:

pub struct CalculatorSettings {
precision: u32,
angle_mode: AngleMode,
notation: NumberFormat,
}
impl CalculatorSettings {
pub fn instance() -> &'static mut Self {
static mut INSTANCE: Option<CalculatorSettings> = None;
unsafe {
INSTANCE.get_or_insert_with(|| Self {
precision: 10,
angle_mode: AngleMode::Radians,
notation: NumberFormat::Decimal,
})
}
}
}

This traditional Singleton approach requires unsafe because we’re creating a mutable static variable. Rust’s safety guarantees don’t extend into unsafe blocks, so we lose the compiler’s help in preventing data races.

This code has several issues. Most glaringly, it requires unsafe code. It’s also not thread-safe. This will be extremely difficult to test, and it is much more difficult to reason about, for many reasons, but noticeably, because it hides dependencies.

Instead of forcing a Singleton pattern, let’s consider what we’re really trying to achieve. Let’s try building something more robust that actually does what we need it to do. We can begin by creating a way to configure calculators:

#[derive(Clone, Debug)]
pub struct CalculatorConfig {
precision: u32,
angle_mode: AngleMode,
notation: NumberFormat,
}
impl Default for CalculatorConfig {
fn default() -> Self {
Self {
precision: 10,
angle_mode: AngleMode::Radians,
notation: NumberFormat::Decimal,
}
}
}

This CalculatorConfig struct replaces the mutable global state of a singleton with an explicit, copyable configuration object. The Default implementation provides sensible initial values that any code can use without accessing global state. Because the struct is Clone, each calculator can have its own copy of the configuration, eliminating shared mutable state entirely.

With our calculator config in place, we can begin working on the calculator itself:

pub struct Calculator<F: TokenFactory> {
config: CalculatorConfig,
factory: F,
expression: Vec<Token>,
}
impl<F: TokenFactory> Calculator<F> {
pub fn new(factory: F) -> Self {
Self {
config: CalculatorConfig::default(),
factory,
expression: Vec::new(),
}
}
pub fn with_config(factory: F, config: CalculatorConfig) -> Self {
Self {
config,
factory,
expression: Vec::new(),
}
}
}

The Calculator struct takes configuration explicitly through its constructor. The new method uses the default configuration, while with_config accepts custom settings. This dependency injection approach makes the calculator’s requirements visible in its API. It has no hidden global state that might change unexpectedly. Testing becomes straightforward because you can create calculators with any configuration you need.

Now we can create a pool of calculators:

use std::sync::Arc;
pub struct CalculatorPool {
shared_config: Arc<CalculatorConfig>,
calculators: Vec<Calculator<StandardFactory>>,
}
impl CalculatorPool {
pub fn new(config: CalculatorConfig) -> Self {
Self {
shared_config: Arc::new(config),
calculators: Vec::new(),
}
}
pub fn new_calculator(&mut self) -> Calculator<StandardFactory> {
let calc = Calculator::with_config(
StandardFactory,
(*self.shared_config).clone()
);
self.calculators.push(calc.clone());
calc
}
}

The pool gives us the benefits of shared configuration without the drawbacks of a true singleton. Each calculator owns its config (cloned from the shared Arc), so there’s no mutable global state. We can easily test calculators in isolation and reason about their behavior. Where we really need shared settings, we can share the Arc directly.

If we need global constants, we can use a const:

pub const DEFAULT_PRECISION: u32 = 10;
pub const MAX_PRECISION: u32 = 100;
pub mod defaults {
use super::*;
pub const CONFIG: CalculatorConfig = CalculatorConfig {
precision: DEFAULT_PRECISION,
angle_mode: AngleMode::Radians,
notation: NumberFormat::Decimal,
};
}

For configuration, that must be loaded at runtime:

use std::sync::OnceLock;
static CONFIG: OnceLock<CalculatorConfig> = OnceLock::new();
pub fn get_config() -> &'static CalculatorConfig {
CONFIG.get_or_init(|| {
// Load from file, environment, etc.
CalculatorConfig::default()
})
}

OnceLock (from std::sync) provides thread-safe, one-time initialization of a value. Unlike a regular static variable, OnceLock allows the value to be computed at runtime (for example, loaded from a configuration file). The get_or_init method ensures the initialization closure runs exactly once, even if multiple threads call it simultaneously. This is the safe, idiomatic replacement for the lazy static pattern.

This approach offers several advantages. Configuration is explicit in the API, making the code clear, as well as the dependencies. Testing is also straightforward, which promotes safer code. Thread-safety is guaranteed by the type system.

Rust’s type system and module system often provide better solutions than the Singleton pattern. We can use const for compile-time constants, and OnceLock or Mutex for runtime-initialized globals (but we should also consider whether the state really needs to be global at all). We can share the state with Arc, and we can pass the configuration explicitly where needed.

In the next section, we’ll look at the Prototype pattern and see how Rust’s traits often provide a better alternative.

In this section, we’ll explore the Prototype pattern and its relationship with Rust’s built-in traits. While Prototype is traditionally used to clone objects in object-oriented languages, Rust’s Clone and Default traits often provide better alternatives. We’ll see how these traits give us the benefits of the Prototype pattern while maintaining Rust’s safety and clarity.

The Prototype pattern traditionally allows creating new objects by cloning existing ones. In our calculator, we might want to create new expressions based on existing ones while sharing common subexpressions. We could also provide template expressions for common calculations.

Let’s see how Rust’s traits help us achieve the Prototype pattern’s goals. The first step is making our Expression type cloneable, which #[derive(Clone)] handles automatically. This alone gives us basic prototype functionality. Any expression can serve as a template for new expressions:

#[derive(Clone)]
pub struct Expression<F: TokenFactory> {
tokens: Vec<Token>,
factory: F,
}
// Templates for common expressions
impl<F: TokenFactory> Expression<F> {
pub fn quadratic_template(factory: F) -> Result<ExpressionBuilder<F>, String> {
Ok(Expression::builder(factory)
.number("1")? // Default coefficient
.operator("*")?
.variable("x")?
.operator("^")?
.number("2")?
.operator("+")?
.number("0")? // Default coefficient
.operator("*")?
.variable("x")?
.operator("+")?
.number("0")?) // Default coefficient
}
}
// Using the template
let expr = Expression::quadratic_template(StandardFactory)?
.build()?;
// Clone and modify
let mut expr2 = expr.clone();
expr2.set_coefficient(2, -4.0)?; // Set constant term

The quadratic_template method creates a prototype for quadratic expressions (ax2+bx+cax^{2}+bx+c) with placeholder coefficients. We can clone this template and modify the coefficients to create specific quadratics such as x2−4x^{2}-4 or 2x2+3x+12x^{2}+3x+1. The builder returns before calling build(), allowing further customization before finalizing the expression.

We can also create subexpressions that can be reused:

#[derive(Clone)]
pub struct SubExpression<F: TokenFactory> {
tokens: Vec<Token>,
factory: F,
}
impl<F: TokenFactory> SubExpression<F> {
pub fn new(tokens: Vec<Token>, factory: F) -> Self {
Self { tokens, factory }
}
// Insert this subexpression into a larger expression
pub fn insert_into(self, mut builder: ExpressionBuilder<F>) -> ExpressionBuilder<F> {
builder.extend(self.tokens)
}
}
// Create a reusable subexpression
let squared = SubExpression::new(
vec![
Token::Variable("x".to_string()),
Token::Operator(Operator::Power),
Token::Number(StandardNumber(2.0)),
],
StandardFactory,
);

The SubExpression type takes the prototype concept further by representing reusable expression fragments. The squared subexpression (x2x^2) can be cloned and inserted into multiple larger expressions. The insert_into method consumes the subexpression, moving its tokens into the builder. For reuse, we clone the subexpression first, preserving the original for additional uses.

We can use it in multiple expressions:

let expr1 = Expression::builder(StandardFactory)
.extend(squared.clone().tokens)
.operator("+")?
.number("1")?
.build()?;
let expr2 = Expression::builder(StandardFactory)
.number("2")?
.operator("*")?
.extend(squared.tokens)
.build()?;

This reusable SubExpression demonstrates how Clone enables the Prototype pattern naturally. We create the squared subexpression once, then clone it for each use. The original remains available for further cloning.

But Rust offers even more with the Default trait:

#[derive(Clone, Default)]
pub struct CalculatorConfig {
precision: u32,
angle_mode: AngleMode,
notation: NumberFormat,
}
impl CalculatorConfig {
pub fn scientific() -> Self {
Self {
precision: 15,
angle_mode: AngleMode::Radians,
notation: NumberFormat::Scientific,
..Default::default()
}
}
pub fn engineering() -> Self {
Self {
notation: NumberFormat::Engineering,
..Default::default()
}
}
}
// Using default and variants
let default_calc = Calculator::new(StandardFactory);
let scientific_calc = Calculator::with_config(
ScientificFactory,
CalculatorConfig::scientific(),
);

The ..Default::default() syntax is Rust’s struct update syntax combined with the Default trait. It fills in any unspecified fields with their default values. This pattern is particularly useful for configuration types where you want to override just a few fields while keeping sensible defaults for the rest.

The combination of Clone and Default gives us several advantages over the traditional Prototype pattern. Now we have clear ownership semantics and type safety. The new design is also thread-safe and memory-efficient.

For situations where we need shared ownership across threads, we have Arc to hold prototype instances safely. There is also the extremely useful (but often overlooked) Cow for clone-on-write semantics.

Clone-on-write (Cow) is a smart pointer that can hold either borrowed or owned data. When you need to read the data, it uses the borrowed reference directly. Only when you need to modify the data does it clone to create an owned copy. This is particularly useful for strings and slices where you often pass data through unchanged but occasionally need to modify it:

use std::borrow::Cow;
fn maybe_uppercase(s: Cow<str>) -> Cow<str> {
if s.chars().any(|c| c.is_lowercase()) {
Cow::Owned(s.to_uppercase()) // Clones only if needed
} else {
s // Returns borrowed data unchanged
}
}

The maybe_uppercase function demonstrates Cow’s efficiency. If the input string is already uppercase, it returns the borrowed data unchanged – no allocation occurs. Only when modification is needed (lowercase characters exist) does it create a new owned String. This pattern is ideal for functions that usually pass data through unchanged but occasionally need to transform it.

Here’s how we might use these:

// Small tokens can be Copy
#[derive(Copy, Clone)]
pub struct SimpleNumber(f64);
// Shared expression templates
pub struct ExpressionTemplate {
template: Arc<Expression<StandardFactory>>,
}
impl ExpressionTemplate {
pub fn instantiate(&self) -> Expression<StandardFactory> {
(*self.template).clone()
}
}
// Efficient string handling in tokens
use std::borrow::Cow;
pub struct VariableToken<'a> {
name: Cow<'a, str>,
value: f64,
}
impl<'a> VariableToken<'a> {
pub fn new(name: impl Into<Cow<'a, str>>, value: f64) -> Self {
Self {
name: name.into(),
value,
}
}
}

These examples show different prototype strategies for different situations. SimpleNumber uses Copy for zero-cost duplication of small values. ExpressionTemplate uses Arc to share complex expression trees across multiple uses without deep cloning. VariableToken uses Cow to efficiently handle variable names that are usually borrowed from the parser but occasionally need to be owned. Together, these patterns provide the flexibility of the Prototype pattern with Rust’s safety guarantees.

Thus, Rust’s built-in traits provide most of what we need from the Prototype pattern, but with better safety guarantees and clearer semantics. Instead of creating a custom cloning system, we can use Clone for general copying, Copy for trivial types, Default for template objects, Arc for shared templates, and Cow for efficient string handling.

In this chapter, we explored how traditional creational patterns translate to Rust, using our Correct Calculator project as a practical example. We saw that while some patterns need adaptation, others can be replaced by Rust’s language features.

We examined Factory Method and how it works naturally with Rust’s enum constructors. We also discussed Abstract Factory and its implementation using traits and associated types. We talked about the Builder pattern and how it benefits from Rust’s ownership system, and explored why Singleton is usually unnecessary in Rust. Finally, we discussed how Rust’s traits can replace the need for the traditional Prototype pattern.

In the next chapter, we’ll explore structural patterns and see how they can help us organize our calculator’s components effectively.