The Pattern Map
State, Iterator, Memento, Visitor and Interpreter, from Undo Stacks to Agent Rewind
October 22, 2026 · 20 min read
Design Patterns, C#, Python, Swift, AI Agents, Software Architecture
Part of The Pattern Map: GoF → Cloud → AI. The hub links every pattern in the series.
This post finishes the Gang of Four catalogue. Five patterns, which is a lot for one post, but two of them (Iterator and Visitor) are so built into modern languages that the honest answer is often "you already use it, here's what it's called".
The new clothes this time:
- State: an agent run moves through idle, thinking, waiting for approval, running a tool, done.
- Iterator: streaming tokens and paginated APIs.
await foreach,async for,for await. - Memento: agent checkpoints. Rewind to before the last prompt.
- Visitor: walking the syntax tree of code a model just wrote, before you run it.
- Interpreter: letting a model write a filter in a tiny language you evaluate safely, instead of
eval.
Same format as before: the problem, C# and Python (Swift where it's natural), an "in Python you often don't need this" note where true, and where you'll meet it now.
State
The problem
An object behaves differently depending on what state it's in, and the logic is spread across switch (status) blocks in every method. Add a state and you have to find all of them. Miss one and you get a bug like "the cancel button works after the run finished".
State moves each state's behaviour into its own object. The context holds the current state and delegates to it. A transition is just swapping which object it holds.
C#
An agent run is a good example because it really does have distinct modes, and the UI should show something different in each:
var run = new AgentRun();
foreach (var e in new[] { RunEvent.UserMessage, RunEvent.ToolRequested, RunEvent.Approved,
RunEvent.ToolFinished, RunEvent.FinalAnswer, RunEvent.ToolRequested })
run.Handle(e);
public enum RunEvent { UserMessage, ToolRequested, Approved, Denied, ToolFinished, FinalAnswer }
// Each state owns its own behaviour: what it shows, and what each event leads to.
public interface IRunState
{
string Status { get; }
IRunState? On(RunEvent e); // null = this event isn't valid here
}
public class Idle : IRunState
{
public string Status => "Ready";
public IRunState? On(RunEvent e) => e == RunEvent.UserMessage ? new Thinking() : null;
}
public class Thinking : IRunState
{
public string Status => "Thinking...";
public IRunState? On(RunEvent e) => e switch
{
RunEvent.ToolRequested => new AwaitingApproval(),
RunEvent.FinalAnswer => new Done(),
_ => null,
};
}
public class AwaitingApproval : IRunState
{
public string Status => "Waiting for you to approve a tool call";
public IRunState? On(RunEvent e) => e switch
{
RunEvent.Approved => new RunningTool(),
RunEvent.Denied => new Thinking(),
_ => null,
};
}
public class RunningTool : IRunState
{
public string Status => "Running tool...";
public IRunState? On(RunEvent e) => e == RunEvent.ToolFinished ? new Thinking() : null;
}
public class Done : IRunState
{
public string Status => "Done";
public IRunState? On(RunEvent e) => null; // terminal
}
// The context: delegates to whatever state it's in. No switch on "current state" here.
public class AgentRun
{
private IRunState _state = new Idle();
public void Handle(RunEvent e)
{
var next = _state.On(e);
if (next is null) { Console.WriteLine($" ignored {e} while '{_state.Status}'"); return; }
_state = next;
Console.WriteLine($"{e,-14} -> {_state.Status}");
}
}
The last event is a tool request after the run is done, and it's ignored because Done doesn't accept anything. The bug class "action allowed in the wrong state" is gone by construction.
Python
TRANSITIONS = {
("idle", "user_message"): "thinking",
("thinking", "tool_requested"): "awaiting_approval",
("thinking", "final_answer"): "done",
("awaiting_approval", "approved"): "running_tool",
("awaiting_approval", "denied"): "thinking",
("running_tool", "tool_finished"): "thinking",
}
class AgentRun:
def __init__(self):
self.state = "idle"
def handle(self, event: str):
next_state = TRANSITIONS.get((self.state, event))
if next_state is None:
print(f" ignored {event} while {self.state}")
return
self.state = next_state
print(f"{event:<15} -> {self.state}")
run = AgentRun()
for e in ["user_message", "tool_requested", "approved",
"tool_finished", "final_answer", "tool_requested"]:
run.handle(e)
In Python you often don't need this. When states differ only in where they go next, a transition table (a dict keyed by (state, event)) is shorter and easier to read than five classes. Reach for state classes when each state has real behaviour of its own, not just a different next hop.
Swift
Swift enums with associated values are the most natural fit of the three, because each state can carry its own data and the compiler checks the switch:
enum RunState: Equatable {
case idle
case thinking
case awaitingApproval(tool: String)
case runningTool(tool: String)
case done(answer: String)
}
enum RunEvent {
case userMessage
case toolRequested(String)
case approved, denied
case toolFinished
case finalAnswer(String)
}
extension RunState {
/// Returns nil if the event isn't valid in this state.
func on(_ event: RunEvent) -> RunState? {
switch (self, event) {
case (.idle, .userMessage): return .thinking
case (.thinking, .toolRequested(let tool)): return .awaitingApproval(tool: tool)
case (.thinking, .finalAnswer(let answer)): return .done(answer: answer)
case (.awaitingApproval(let tool), .approved): return .runningTool(tool: tool)
case (.awaitingApproval, .denied): return .thinking
case (.runningTool, .toolFinished): return .thinking
default: return nil
}
}
}
var state = RunState.idle
let events: [RunEvent] = [.userMessage, .toolRequested("create_reminder"), .approved,
.toolFinished, .finalAnswer("Reminder set."), .userMessage]
for event in events {
if let next = state.on(event) { state = next; print(state) }
else { print(" ignored \(event) in \(state)") }
}
Put a RunState in an @Observable model and a SwiftUI view can switch on it to show a spinner, an approval sheet or the answer. Note that awaitingApproval carries the tool name, so the approval sheet knows what to ask about. Data that only exists in one state lives in that state.
Where you'll see it now: agent frameworks model runs as explicit state machines. LangGraph, for example, is built around a graph of nodes and a state object that moves between them. Even if you don't use a framework, writing your agent loop as a state machine makes "waiting for human approval" a real state instead of a flag.
Iterator
The problem
You want to walk through a collection without knowing how it's stored: an array, a tree, or a paginated API where the "collection" is fetched one page at a time with cursors. Without Iterator, every caller re-implements the cursor loop.
C#
yield return writes the iterator for you. With IAsyncEnumerable, the items can arrive over the network:
var count = 0;
await foreach (var message in Inbox.AllMessages())
{
Console.WriteLine($" {message}");
if (++count == 4) break; // stop early: the third page is never fetched
}
public static class Inbox
{
// Fake API: 3 pages of 3 messages, each page returns a cursor to the next.
private static async Task<(string[] Items, int? Next)> FetchPage(int page)
{
Console.WriteLine($"fetching page {page}");
await Task.Delay(10);
string[] items = [$"msg {page * 3 + 1}", $"msg {page * 3 + 2}", $"msg {page * 3 + 3}"];
return (items, page < 2 ? page + 1 : null);
}
// The iterator: callers see one flat stream and never touch cursors.
public static async IAsyncEnumerable<string> AllMessages()
{
int? page = 0;
while (page is int p)
{
var (items, next) = await FetchPage(p);
foreach (var item in items) yield return item;
page = next;
}
}
}
The output shows the useful property: fetching page 0, three messages, fetching page 1, one message, stop. It's lazy. Pages you don't consume are never requested.
Python
from itertools import islice
def fetch_page(page: int) -> tuple[list[str], int | None]:
print(f"fetching page {page}")
items = [f"msg {page * 3 + i}" for i in (1, 2, 3)]
return items, (page + 1 if page < 2 else None)
def all_messages():
"""A generator IS an iterator: the cursor bookkeeping lives here, once."""
page = 0
while page is not None:
items, page = fetch_page(page)
yield from items
for message in islice(all_messages(), 4): # the third page is never fetched
print(" ", message)
In Python you often don't need this. Generators are the Iterator pattern, built into the language. You never write a class with __iter__ and __next__ unless you need something unusual. itertools gives you the operations (islice, chain, groupby) for free. C#'s yield return and LINQ are the same idea in .NET clothes.
Swift: streaming tokens
Swift's AsyncSequence is the async iterator, and it's the shape every streaming model reply takes:
// A fake streaming model: yields one token at a time.
func streamReply(_ text: String) -> AsyncStream<String> {
AsyncStream { continuation in
Task {
for word in text.split(separator: " ") {
try? await Task.sleep(for: .milliseconds(30))
continuation.yield(word + " ")
}
continuation.finish()
}
}
}
var reply = ""
for await token in streamReply("Your reminder is set for January 15.") {
reply += token
print(reply) // in SwiftUI, this would update a Text view
}
Where you'll see it now: every streaming LLM API. The Anthropic Python SDK gives you a text_stream you loop over, .NET's IChatClient has a streaming method that returns an IAsyncEnumerable, and in Swift you wrap the server-sent events in an AsyncSequence. The caller just writes a loop. That's Iterator doing its job.
Memento
The problem
You want to save an object's state so you can go back to it later, without exposing its internals to whoever stores the snapshot. Undo in an editor, "discard changes" in a settings screen, a save point in a game.
Three roles:
- Originator: the object whose state you save. It creates and restores mementos.
- Memento: the snapshot. Opaque to everyone but the originator.
- Caretaker: holds the mementos (a stack, a list per turn) but never looks inside.
The difference from Command's undo: Command stores how to reverse an action. Memento stores the whole state before it. Memento is simpler and more reliable when actions are hard to reverse. It costs memory, which immutable data structures make cheap.
C#
using System.Collections.Immutable;
var ws = new Workspace();
var checkpoints = new Stack<Workspace.Checkpoint>(); // the caretaker
checkpoints.Push(ws.Save());
ws.Edit("Login.swift", "// first try");
checkpoints.Push(ws.Save());
ws.Edit("Login.swift", "// second try, broke the build");
ws.Edit("Auth.swift", "// collateral damage");
Console.WriteLine(ws);
ws.Restore(checkpoints.Pop()); // rewind one turn
Console.WriteLine(ws);
// The originator: the only class that knows what a checkpoint contains.
public class Workspace
{
private ImmutableDictionary<string, string> _files = ImmutableDictionary<string, string>.Empty;
public void Edit(string path, string content) => _files = _files.SetItem(path, content);
// Opaque to everyone else: callers can hold one, but can't read or change it.
public sealed class Checkpoint
{
internal Checkpoint(ImmutableDictionary<string, string> files) => Files = files;
internal ImmutableDictionary<string, string> Files { get; }
}
public Checkpoint Save() => new(_files); // cheap: immutable, no deep copy
public void Restore(Checkpoint c) => _files = c.Files;
public override string ToString() =>
string.Join(" | ", _files.OrderBy(f => f.Key).Select(f => $"{f.Key}: {f.Value}"));
}
After the restore, Auth.swift is gone and Login.swift is back to // first try. Because the dictionary is immutable, saving a checkpoint is just keeping a reference. Nothing is copied.
Python
from dataclasses import dataclass, field, replace
from types import MappingProxyType
@dataclass(frozen=True)
class AgentState:
"""Immutable: every state is already a safe snapshot."""
files: MappingProxyType = field(default_factory=lambda: MappingProxyType({}))
messages: tuple = ()
def edit(self, path: str, content: str) -> "AgentState":
return replace(self, files=MappingProxyType({**self.files, path: content}))
def say(self, role: str, text: str) -> "AgentState":
return replace(self, messages=self.messages + ((role, text),))
history = [AgentState()] # one checkpoint per turn
s = history[-1].say("user", "Add a login screen").edit("Login.swift", "// v1")
history.append(s)
s = s.say("user", "Now add Face ID").edit("Login.swift", "// v2, broken")
history.append(s)
rewound = history[1] # /rewind to after turn 1
print(dict(rewound.files), len(rewound.messages)) # {'Login.swift': '// v1'} 1
In Python you often don't need this as a separate class. If the state is immutable (a frozen dataclass), every state is its own memento, and the caretaker is a list. For mutable state, copy.deepcopy gives you a snapshot in one line, as long as you remember it can be slow on large objects. (MappingProxyType above is only a read-only view. It stops callers from editing the dict through the snapshot.)
Where you'll see it now: agent checkpoints and rewind
This is the clearest new-clothes case in the whole series. Claude Code's checkpointing captures the state of your code before each prompt you send. Run /rewind, or press Esc twice, and you can restore the code, the conversation, or both, to any earlier prompt. That's Memento with the session as the caretaker.
The docs' list of limitations is a good lesson in the pattern too. Checkpoints track edits made through Claude's file-editing tools. Files changed by Bash commands (rm, mv, cp) aren't tracked, and neither are edits you make outside the session. In pattern terms: a memento can only restore state the originator owns. If something else changed the world behind the originator's back, the snapshot doesn't know. That's why the docs say checkpoints aren't a replacement for git.
LangGraph has the same idea as a framework feature: checkpointers save a thread's graph state as checkpoints, which is what makes resuming, human-in-the-loop pauses and "time travel" possible.
Visitor
The problem
You have a stable set of node types (the parts of a document, the nodes of a syntax tree) and a growing list of operations over them: count words, render Markdown, render HTML, find broken links. Putting every operation as a method on every node class means editing all of them each time.
Visitor flips it. Each node has one Accept(visitor) method. Each operation is a visitor class with one Visit method per node type. A new operation is a new visitor, and the node classes don't change. The trick that makes it work is double dispatch: node.Accept(v) calls v.Visit(this), and the compiler picks the right overload because inside each node class, this has a known type.
C#: the classic version
INode[] doc =
[
new Heading("Release notes"),
new Paragraph("Dark mode is here and sync is faster."),
new CodeBlock("swift", "let theme = Theme.dark"),
];
var words = new WordCounter();
foreach (var node in doc) node.Accept(words);
Console.WriteLine($"words: {words.Total}");
var md = new MarkdownRenderer();
foreach (var node in doc) node.Accept(md);
Console.Write(md.Output);
// The element classes stay small and stable. Each just says "visit me as what I am".
public interface INode { void Accept(IVisitor v); }
public record Heading(string Text) : INode { public void Accept(IVisitor v) => v.Visit(this); }
public record Paragraph(string Text) : INode { public void Accept(IVisitor v) => v.Visit(this); }
public record CodeBlock(string Lang, string Code) : INode { public void Accept(IVisitor v) => v.Visit(this); }
// A new operation = a new visitor. No node class changes.
public interface IVisitor
{
void Visit(Heading h);
void Visit(Paragraph p);
void Visit(CodeBlock c);
}
public class WordCounter : IVisitor
{
public int Total { get; private set; }
private static int Count(string s) => s.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length;
public void Visit(Heading h) => Total += Count(h.Text);
public void Visit(Paragraph p) => Total += Count(p.Text);
public void Visit(CodeBlock c) { } // code doesn't count as prose
}
public class MarkdownRenderer : IVisitor
{
public string Output { get; private set; } = "";
public void Visit(Heading h) => Output += $"# {h.Text}\n\n";
public void Visit(Paragraph p) => Output += $"{p.Text}\n\n";
public void Visit(CodeBlock c) => Output += $"```{c.Lang}\n{c.Code}\n```\n";
}
C#: the modern version
Since C# got pattern matching, I'd write most small visitors as a switch expression over records instead:
Node[] doc = [new Heading("Release notes"), new Paragraph("Dark mode is here."), new CodeBlock("swift", "let x = 1")];
static int Words(Node n) => n switch
{
Heading h => h.Text.Split(' ').Length,
Paragraph p => p.Text.Split(' ').Length,
CodeBlock => 0,
_ => throw new ArgumentOutOfRangeException(nameof(n)),
};
Console.WriteLine(doc.Sum(Words)); // 6
public abstract record Node;
public record Heading(string Text) : Node;
public record Paragraph(string Text) : Node;
public record CodeBlock(string Lang, string Code) : Node;
The trade-off: the classic Visitor makes the compiler complain if you add a node type and forget to handle it in some visitor (the interface gains a method). The switch version needs that _ arm, so a forgotten case becomes a runtime exception. For a big, long-lived tree like a compiler's, the classic form still earns its keep. Roslyn's CSharpSyntaxWalker and SwiftSyntax's SyntaxVisitor are both classic visitors for exactly that reason.
Python
from dataclasses import dataclass
@dataclass
class Heading:
text: str
@dataclass
class Paragraph:
text: str
@dataclass
class CodeBlock:
lang: str
code: str
def word_count(node) -> int:
match node: # structural pattern matching, Python 3.10+
case Heading(text) | Paragraph(text):
return len(text.split())
case CodeBlock():
return 0
raise TypeError(node)
doc = [Heading("Release notes"),
Paragraph("Dark mode is here and sync is faster."),
CodeBlock("swift", "let theme = Theme.dark")]
print("words:", sum(word_count(n) for n in doc)) # words: 10
In Python you often don't need this. There's no method overloading, so classic double dispatch is awkward anyway. A match statement or functools.singledispatch gives you "one function, a case per type" without any accept methods on the nodes.
Where you'll see it now: checking code a model wrote
The one place Python ships a classic visitor is the place it matters most for agents. ast.NodeVisitor walks a syntax tree and calls visit_<NodeType> for each node. That makes it easy to inspect model-generated code before running it:
import ast
RISKY = {"os.system", "subprocess.run", "subprocess.Popen", "eval", "exec", "shutil.rmtree"}
class RiskyCallFinder(ast.NodeVisitor):
"""Python's own Visitor: one visit_<NodeType> method per node type you care about."""
def __init__(self):
self.found: list[str] = []
def visit_Call(self, node: ast.Call):
name = ast.unparse(node.func)
if name in RISKY:
self.found.append(f"line {node.lineno}: {name}")
self.generic_visit(node) # keep walking into arguments
generated = '''
import os, shutil
def clean(path):
print("cleaning", path)
shutil.rmtree(path)
os.system("rm -rf /tmp/cache")
'''
finder = RiskyCallFinder()
finder.visit(ast.parse(generated))
print(finder.found) # ['line 5: shutil.rmtree', 'line 6: os.system']
This is a review aid, not a sandbox. Determined code can hide a call from a name check (getattr(os, "sys" + "tem")). Real isolation comes from where the code runs. But as a first filter, or a way to show a human "this script deletes things", it's a few lines.
Interpreter
The problem
You have a small, recurring kind of problem that's easiest to express as sentences in a tiny language: routing rules, search filters, pricing rules, feature-flag conditions. Interpreter says: define the grammar, make one class per rule of the grammar, and have each class evaluate itself against a context.
The pattern covers the evaluation. Parsing text into the tree is a separate job, and the book assumes you've done it.
C#
A routing rule, tokens > 4000 or (has_image and tier == 'free'), built as a tree by hand:
// "tokens > 4000 or (has_image and tier == 'free')", built by hand.
// A parser would produce this tree; the Interpreter pattern is about evaluating it.
IExpr rule = new Or(
new Greater(new Var("tokens"), new Num(4000)),
new And(new Var("has_image"), new Eq(new Var("tier"), new Str("free"))));
var requests = new[]
{
new Dictionary<string, object> { ["tokens"] = 1200, ["has_image"] = false, ["tier"] = "pro" },
new Dictionary<string, object> { ["tokens"] = 9000, ["has_image"] = false, ["tier"] = "pro" },
new Dictionary<string, object> { ["tokens"] = 300, ["has_image"] = true, ["tier"] = "free" },
};
foreach (var ctx in requests)
Console.WriteLine(rule.Eval(ctx) is true ? "route: big model" : "route: small model");
// One class per grammar rule. Each knows how to evaluate itself.
public interface IExpr { object Eval(IReadOnlyDictionary<string, object> ctx); }
public record Num(int Value) : IExpr { public object Eval(IReadOnlyDictionary<string, object> ctx) => Value; }
public record Str(string Value) : IExpr { public object Eval(IReadOnlyDictionary<string, object> ctx) => Value; }
public record Var(string Name) : IExpr { public object Eval(IReadOnlyDictionary<string, object> ctx) => ctx[Name]; }
public record Greater(IExpr L, IExpr R) : IExpr
{
public object Eval(IReadOnlyDictionary<string, object> ctx) => (int)L.Eval(ctx) > (int)R.Eval(ctx);
}
public record Eq(IExpr L, IExpr R) : IExpr
{
public object Eval(IReadOnlyDictionary<string, object> ctx) => L.Eval(ctx).Equals(R.Eval(ctx));
}
public record And(IExpr L, IExpr R) : IExpr
{
public object Eval(IReadOnlyDictionary<string, object> ctx) => (bool)L.Eval(ctx) && (bool)R.Eval(ctx);
}
public record Or(IExpr L, IExpr R) : IExpr
{
public object Eval(IReadOnlyDictionary<string, object> ctx) => (bool)L.Eval(ctx) || (bool)R.Eval(ctx);
}
Output: small model, big model, big model. Notice how this is Composite (from the Structural II post) with an Eval method. Most interpreters are.
Python
Python's trick is that you don't need to write a parser. ast.parse parses the expression for you, and you interpret only the node types you allow. That's Interpreter and Visitor together:
import ast
import operator
COMPARE = {ast.Gt: operator.gt, ast.Lt: operator.lt, ast.GtE: operator.ge,
ast.LtE: operator.le, ast.Eq: operator.eq, ast.NotEq: operator.ne}
def evaluate(node: ast.AST, ctx: dict):
"""Interpret a tiny, whitelisted subset of Python expressions. Anything else is rejected."""
match node:
case ast.Expression(body):
return evaluate(body, ctx)
case ast.BoolOp(ast.And(), values):
return all(evaluate(v, ctx) for v in values)
case ast.BoolOp(ast.Or(), values):
return any(evaluate(v, ctx) for v in values)
case ast.Compare(left, [op], [right]) if type(op) in COMPARE:
return COMPARE[type(op)](evaluate(left, ctx), evaluate(right, ctx))
case ast.Name(id):
return ctx[id]
case ast.Constant(value) if isinstance(value, (int, float, str, bool)):
return value
raise ValueError(f"not allowed: {ast.dump(node)[:40]}")
def matches(rule: str, ctx: dict) -> bool:
return bool(evaluate(ast.parse(rule, mode="eval"), ctx))
# Say a model turned "night shots on the telephoto" into this filter:
rule = "iso >= 3200 and lens == 'RF 70-200mm F4'"
photos = [{"iso": 6400, "lens": "RF 70-200mm F4"},
{"iso": 6400, "lens": "RF 16-28mm F2.8"},
{"iso": 400, "lens": "RF 70-200mm F4"}]
print([matches(rule, p) for p in photos]) # [True, False, False]
try:
matches("__import__('os').system('rm -rf ~')", {})
except ValueError as e:
print(e)
The second call is rejected because function calls aren't in the whitelist. Only comparisons, and, or, names and plain constants get evaluated.
In Python you often don't need this as a class per grammar rule. Pattern matching on ast nodes is the interpreter, and the parser is free. What you must never do is the shortcut: eval(rule) on text you didn't write.
Where you'll see it now: natural-language features in apps. "Show me night shots on the telephoto" goes to a model, the model returns a filter in a small language you defined, and your interpreter runs it against your data. The model never executes anything. It writes a sentence in a language that can only express what you allowed. Structured outputs and tool schemas push in the same direction: constrain what the model can say, then interpret it yourself.
The full map
That's all 23 Gang of Four patterns covered across the series. These five:
| Pattern | Old clothes | New clothes |
|---|---|---|
| State | Order status, connection lifecycle | Agent run states; approval as a real state |
| Iterator | yield return, generators, pagination | Token streaming (IAsyncEnumerable, async for, AsyncSequence) |
| Memento | Editor undo, save points | Agent checkpoints and /rewind; LangGraph checkpointers |
| Visitor | Compilers, document renderers | Inspecting model-written code with ast.NodeVisitor |
| Interpreter | Rule engines, query DSLs | Model writes a filter, your code interprets it, no eval |
Previous: Command, Chain of Responsibility, Mediator and Template Method. The series moves on to cloud patterns next. The hub has the full list.
Further reading
- The series hub, with every pattern on one page
- Claude Code docs on checkpointing, including what rewind doesn't track
- LangGraph docs on persistence, for checkpointers and threads
- Python docs for the ast module, including
NodeVisitorandparse - Apple developer documentation for AsyncSequence
- Design Patterns: Elements of Reusable Object-Oriented Software (Gamma, Helm, Johnson, Vlissides)
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.