The Pattern Map
Creational Patterns: Abstract Factory, Builder and Prototype
October 8, 2026 · 14 min read
Design Patterns, Software Architecture, C#, Python, Swift, AI
This is the first pattern post in The Pattern Map. Creational patterns are about how objects get made. Two of the five, Factory Method and Singleton, I covered in 5 Design Patterns Every Developer Should Master. This post does the other three:
- Abstract Factory: create families of objects that have to match.
- Builder: assemble a complicated object in steps and validate it once.
- Prototype: make new objects by copying a configured one.
All three examples use the same small domain: the code around an AI feature in an app. It's the kind of code more and more of us are writing now, and it shows each pattern's problem clearly. Every sample below compiles and runs as shown (C# as .NET 10 file-based apps, Python 3.12, Swift 6). The "model" calls are stand-ins so nothing needs a network or an API key.
Abstract Factory
The problem
Factory Method answers "which class do I create?" Abstract Factory answers a bigger question: "which set of classes do I create, so that they work together?"
Here's a real version of that problem. If you add semantic search to an app, you need two things: an embedder that turns text into vectors, and a vector store that holds them. They're not independent choices. A small local model might produce 384-dimension vectors; a hosted one might produce 1,024. An index built for one can't hold vectors from the other. Mixing them is a bug, and often a silent one if your store doesn't check.
Abstract Factory puts "things that must match" behind one object, so the choice is made once.
C#
// Two products that must match: vectors from one embedding model
// only make sense in an index built for that model's dimensions.
public interface IEmbedder
{
int Dimensions { get; }
float[] Embed(string text);
}
public interface IVectorStore
{
void Add(string id, float[] vector);
int Count { get; }
}
// The abstract factory: one method per product in the family.
public interface IAiStackFactory
{
IEmbedder CreateEmbedder();
IVectorStore CreateVectorStore();
}
// Each concrete factory makes a family that fits together.
public sealed class LocalStackFactory : IAiStackFactory
{
public IEmbedder CreateEmbedder() => new FakeEmbedder("local-small", 384);
public IVectorStore CreateVectorStore() => new InMemoryVectorStore(384);
}
public sealed class HostedStackFactory : IAiStackFactory
{
public IEmbedder CreateEmbedder() => new FakeEmbedder("hosted-large", 1024);
public IVectorStore CreateVectorStore() => new InMemoryVectorStore(1024);
}
// Client code only ever sees the interfaces.
public sealed class NotesIndexer(IAiStackFactory stack)
{
private readonly IEmbedder _embedder = stack.CreateEmbedder();
private readonly IVectorStore _store = stack.CreateVectorStore();
public void Index(string id, string text) => _store.Add(id, _embedder.Embed(text));
public int Count => _store.Count;
}
The stand-ins, so it runs without a model:
public sealed class FakeEmbedder(string model, int dimensions) : IEmbedder
{
public int Dimensions => dimensions;
public float[] Embed(string text)
{
var v = new float[dimensions];
for (int i = 0; i < text.Length; i++) v[i % dimensions] += text[i];
return v;
}
public override string ToString() => model;
}
public sealed class InMemoryVectorStore(int dimensions) : IVectorStore
{
private readonly Dictionary<string, float[]> _items = new();
public void Add(string id, float[] vector)
{
if (vector.Length != dimensions)
throw new ArgumentException($"Expected {dimensions} dimensions, got {vector.Length}");
_items[id] = vector;
}
public int Count => _items.Count;
}
And the usage:
// Pick the family once, at the edge of the app (config, DI, a flag).
IAiStackFactory stack = args.Contains("--hosted")
? new HostedStackFactory()
: new LocalStackFactory();
var indexer = new NotesIndexer(stack);
indexer.Index("note-1", "Buy film for Saturday");
indexer.Index("note-2", "Renew the developer account");
Console.WriteLine($"{stack.GetType().Name}: indexed {indexer.Count} notes");
// Without the factory, nothing stops you mixing families:
try
{
var store = new InMemoryVectorStore(1024);
store.Add("oops", new FakeEmbedder("local-small", 384).Embed("hello"));
}
catch (ArgumentException ex)
{
Console.WriteLine($"Mixed families: {ex.Message}");
}
LocalStackFactory: indexed 2 notes
Mixed families: Expected 1024 dimensions, got 384
NotesIndexer never names a concrete class. Switching from local to hosted is one line at startup, and it's impossible to switch only half of the pair. In ASP.NET Core you'd register the factory in DI per environment, and the rest of the app wouldn't know.
Python
from dataclasses import dataclass
from typing import Callable, Protocol
class Embedder(Protocol):
dimensions: int
def embed(self, text: str) -> list[float]: ...
class VectorStore(Protocol):
def add(self, id: str, vector: list[float]) -> None: ...
class FakeEmbedder:
def __init__(self, model: str, dimensions: int):
self.model, self.dimensions = model, dimensions
def embed(self, text: str) -> list[float]:
v = [0.0] * self.dimensions
for i, ch in enumerate(text):
v[i % self.dimensions] += ord(ch)
return v
class InMemoryVectorStore:
def __init__(self, dimensions: int):
self.dimensions, self.items = dimensions, {}
def add(self, id: str, vector: list[float]) -> None:
if len(vector) != self.dimensions:
raise ValueError(f"Expected {self.dimensions} dimensions, got {len(vector)}")
self.items[id] = vector
# The "factory" is just a record of two constructors that belong together.
@dataclass(frozen=True)
class AiStack:
make_embedder: Callable[[], Embedder]
make_store: Callable[[], VectorStore]
STACKS = {
"local": AiStack(lambda: FakeEmbedder("local-small", 384),
lambda: InMemoryVectorStore(384)),
"hosted": AiStack(lambda: FakeEmbedder("hosted-large", 1024),
lambda: InMemoryVectorStore(1024)),
}
def index_notes(stack: AiStack, notes: dict[str, str]) -> VectorStore:
embedder, store = stack.make_embedder(), stack.make_store()
for id, text in notes.items():
store.add(id, embedder.embed(text))
return store
store = index_notes(STACKS["local"], {"note-1": "Buy film", "note-2": "Renew account"})
print(f"local: indexed {len(store.items)} notes")
In Python you often don't need this. There's no factory interface and no factory subclasses here. Classes and functions are already objects you can pass around, so "a family of constructors" is a frozen dataclass of callables, or even just a dict. The idea survives (choose the family once, in one place); the class hierarchy doesn't.
Where you'll see it now: any "kit" that must stay consistent. In the cloud era that's per-environment infrastructure, like the Azurite storage emulator locally and real Azure Storage in production behind the same interfaces. In the AI era, it's a provider kit where the embedder, the index and the tokenizer have to agree.
Builder
The problem
Some objects have many optional parts and some rules that span several of them. A request to a language model is a good example: a model, an optional system prompt, a list of messages, maybe some tools, a token limit. The rules aren't per-field. "There must be at least one message" and "the last message must come from the user" are about the whole object.
A constructor with eight parameters is unreadable, and setting properties one by one lets you create the object in an invalid state. Builder separates assembling from creating: you add parts in any order, and Build() checks the whole thing once and hands back something immutable.
I showed the most common Builder in .NET, WebApplication.CreateBuilder, in Design Patterns I Keep Coming Back To. Here's one you'd write yourself.
C#
public sealed record Message(string Role, string Content);
public sealed record Tool(string Name, string Description);
// The product: immutable, and only ever constructed in a valid state.
public sealed record ChatRequest(
string Model,
string? System,
IReadOnlyList<Message> Messages,
IReadOnlyList<Tool> Tools,
int MaxTokens)
{
public override string ToString() =>
$"{Model}: {Messages.Count} message(s), {Tools.Count} tool(s), max {MaxTokens} tokens";
}
public sealed class ChatRequestBuilder(string model)
{
private string? _system;
private readonly List<Message> _messages = [];
private readonly List<Tool> _tools = [];
private int _maxTokens = 1024;
public ChatRequestBuilder WithSystem(string text) { _system = text; return this; }
public ChatRequestBuilder AddUser(string text) { _messages.Add(new("user", text)); return this; }
public ChatRequestBuilder AddAssistant(string text) { _messages.Add(new("assistant", text)); return this; }
public ChatRequestBuilder WithTool(string name, string description) { _tools.Add(new(name, description)); return this; }
public ChatRequestBuilder WithMaxTokens(int n) { _maxTokens = n; return this; }
// Rules that span several fields live in one place.
public ChatRequest Build()
{
if (_messages.Count == 0)
throw new InvalidOperationException("A request needs at least one message.");
if (_messages[^1].Role != "user")
throw new InvalidOperationException("The last message must come from the user.");
if (_maxTokens <= 0)
throw new InvalidOperationException("MaxTokens must be positive.");
return new ChatRequest(model, _system, _messages.ToArray(), _tools.ToArray(), _maxTokens);
}
}
var request = new ChatRequestBuilder("my-model")
.WithSystem("You are a terse release-notes writer.")
.AddUser("Summarise these commits: ...")
.WithTool("get_commit", "Fetch one commit by SHA")
.WithMaxTokens(800)
.Build();
Console.WriteLine(request);
try
{
new ChatRequestBuilder("my-model").WithSystem("No user message yet").Build();
}
catch (InvalidOperationException ex)
{
Console.WriteLine($"Rejected: {ex.Message}");
}
my-model: 1 message(s), 1 tool(s), max 800 tokens
Rejected: A request needs at least one message.
Two details matter. Build() copies the lists with ToArray(), so changing the builder afterwards can't change a request you already built. And the product is a record with no public setters, so "valid at construction" means "valid forever".
Modern C# shrinks the need for this. If your rules are all per-field, a record with required init-only properties and object-initializer syntax is enough. Builder earns its place when there are cross-field rules or when the object is assembled over time, across several methods.
Python
from dataclasses import dataclass
@dataclass(frozen=True)
class ChatRequest:
model: str
messages: tuple[dict, ...]
system: str | None = None
tools: tuple[dict, ...] = ()
max_tokens: int = 1024
def __post_init__(self):
if not self.messages:
raise ValueError("A request needs at least one message.")
if self.messages[-1]["role"] != "user":
raise ValueError("The last message must come from the user.")
if self.max_tokens <= 0:
raise ValueError("max_tokens must be positive.")
request = ChatRequest(
model="my-model",
system="You are a terse release-notes writer.",
messages=({"role": "user", "content": "Summarise these commits: ..."},),
tools=({"name": "get_commit", "description": "Fetch one commit by SHA"},),
max_tokens=800,
)
print(f"{request.model}: {len(request.messages)} message(s), max {request.max_tokens} tokens")
try:
ChatRequest(model="my-model", messages=())
except ValueError as e:
print(f"Rejected: {e}")
my-model: 1 message(s), max 800 tokens
Rejected: A request needs at least one message.
In Python you often don't need this. Keyword arguments with defaults already solve the "eight positional parameters" problem, and __post_init__ on a frozen dataclass gives you the one-place validation. That covers most of what Builder is for. You'd still reach for a builder when the object is genuinely assembled step by step, say a prompt that different functions each add a section to.
Swift is similar: memberwise initializers with default values cover most cases. Swift's "result builders" (the thing behind SwiftUI's view syntax) share the name but are a language feature for building values from a block of statements, not this pattern.
Where you'll see it now: SDK client options and infrastructure-as-code constructs in the cloud era; request and prompt builders in AI code, where "the conversation must end with a user turn" is exactly the kind of cross-field rule Builder exists for.
Prototype
The problem
Sometimes the expensive part of an object is its configuration, not its construction. You tune a base setup carefully, then want ten variations that differ in one or two fields. Prototype says: don't rebuild from scratch, copy the configured one and change what's different.
The pattern is easy. The trap is the copy. A shallow copy duplicates the top-level fields but shares anything they point to. If the prototype holds a list, every "copy" holds the same list.
Here's a version of that bug that matters in agent code. You have a base agent profile with a tool allowlist. You copy it to make a second agent and give the copy one more tool. With a shallow copy, the original silently gains that tool too.
C#
// A carefully configured base agent: the prototype.
var baseAgent = new AgentProfile(
Model: "my-model",
SystemPrompt: "You review Swift code. Be specific.",
AllowedTools: ["read_file", "search"]);
// Shallow clone: `with` copies the reference to the same List.
var leaky = baseAgent with { SystemPrompt = "You write release notes." };
leaky.AllowedTools.Add("write_file");
Console.WriteLine($"base after shallow clone: {string.Join(", ", baseAgent.AllowedTools)}");
// Deep clone: copy the mutable parts yourself.
var reviewer = new AgentProfile("my-model", "You review Swift code. Be specific.", ["read_file", "search"]);
var writer = reviewer.DeepCopy() with { SystemPrompt = "You write release notes." };
writer.AllowedTools.Add("write_file");
Console.WriteLine($"base after deep clone: {string.Join(", ", reviewer.AllowedTools)}");
Console.WriteLine($"writer: {string.Join(", ", writer.AllowedTools)}");
public sealed record AgentProfile(string Model, string SystemPrompt, List<string> AllowedTools)
{
public AgentProfile DeepCopy() => this with { AllowedTools = [.. AllowedTools] };
}
base after shallow clone: read_file, search, write_file
base after deep clone: read_file, search
writer: read_file, search, write_file
The reviewer agent just gained write_file because someone configured a different agent. That's the whole pattern's risk in one line of output.
C#'s with expression is built-in Prototype: it copies a record and lets you change some fields. Microsoft's docs spell out that a reference-type member is copied by reference, so the original and the copy share the same instance: a shallow copy. Three fixes: copy mutable members yourself, as DeepCopy() does; declare your own copy constructor on the record, which with will then use (the docs show this); or don't put mutable collections in records at all (ImmutableArray<string>, say), so there's nothing to share by accident.
One gotcha: you can't call that method Clone(). The compiler rejects it (error CS8859). Records reserve the name, because the compiler generates its own hidden clone method to implement with.
Python
import copy
from dataclasses import dataclass, field, replace
@dataclass
class AgentProfile:
model: str
system_prompt: str
allowed_tools: list[str] = field(default_factory=list)
base = AgentProfile("my-model", "You review Swift code. Be specific.", ["read_file", "search"])
# replace() and copy.copy() are shallow: the list is shared.
leaky = replace(base, system_prompt="You write release notes.")
leaky.allowed_tools.append("write_file")
print("base after shallow copy:", base.allowed_tools)
# copy.deepcopy() walks the whole object graph.
base = AgentProfile("my-model", "You review Swift code. Be specific.", ["read_file", "search"])
writer = copy.deepcopy(base)
writer.system_prompt = "You write release notes."
writer.allowed_tools.append("write_file")
print("base after deep copy: ", base.allowed_tools)
print("writer: ", writer.allowed_tools)
base after shallow copy: ['read_file', 'search', 'write_file']
base after deep copy: ['read_file', 'search']
writer: ['read_file', 'search', 'write_file']
In Python you often don't need this. You never write a clone() method; the standard library's copy module is the Prototype pattern, for any object. What you do need is to know which copy you're getting. dataclasses.replace() looks like C#'s with, and it's shallow in exactly the same way.
Swift
This is the one pattern where Swift has a real advantage, so it gets its own example.
struct AgentProfile {
var model: String
var systemPrompt: String
var allowedTools: [String]
}
let base = AgentProfile(
model: "my-model",
systemPrompt: "You review Swift code. Be specific.",
allowedTools: ["read_file", "search"])
// Structs and Arrays are value types: assignment is already a clone.
var writer = base
writer.systemPrompt = "You write release notes."
writer.allowedTools.append("write_file")
print("base: ", base.allowedTools)
print("writer:", writer.allowedTools)
base: ["read_file", "search"]
writer: ["read_file", "search", "write_file"]
No clone(), no deep-copy helper, no bug. Swift's structs and standard collections are value types: assigning one gives you an independent copy (cheaply, because arrays copy on write, only when one side actually changes). Prototype is mostly a language default here. It only comes back if the struct holds a class instance, because class references are shared just like in C# and Python.
Where you'll see it now: in the cloud era, VM and container images and the Deployment Stamps pattern, where you configure one copy and stamp out identical ones. In the AI era, spawning a subagent from a base configuration, or forking a conversation to try two directions from the same point. The shallow-copy question is the first thing I'd check in any of them.
The three side by side
| Solves | C# today | Python today | Swift today | |
|---|---|---|---|---|
| Abstract Factory | Families of objects that must match | Interfaces + DI per environment | A dict or dataclass of callables | Protocols, same idea as C# |
| Builder | Complex object, cross-field rules | Builder for cross-field rules, required init for the rest | Keyword args + __post_init__ | Memberwise init with defaults |
| Prototype | Copy a configured object | with (shallow) + explicit deep copy | copy.deepcopy | Value types do it for you |
Next in the series: Adapter, Facade and Proxy, the three structural patterns that turn out to describe most of the plumbing in AI apps, MCP included. The full list is on The Pattern Map.
Further reading
- Design Patterns: Elements of Reusable Object-Oriented Software by Gamma, Helm, Johnson and Vlissides (1994), chapter 3 covers all five creational patterns.
- Refactoring.Guru on Abstract Factory, Builder and Prototype.
- Microsoft's reference for the C#
withexpression, including how reference-type members are copied and how to customise it with a copy constructor. - Python's
copymodule documentation, on shallow versus deep copies.
Thoughts on this?
Tell me on X: @bobbyencoded · Share this post on X
Want more like this? Subscribe to The Decode, a weekly email on the AI and developer news worth your time.