← Simulation
Foundations →
Chapter 39
Pattern Catalog
Most patterns you will encounter first as a name someone uses in
a design review, not as code. This catalog gives each name a
one-line intent, so you can place it and look it up.
In This Chapter
This chapter gathers patterns that the literature documents
widely, not only the original Design Patterns (GoF)
set. It draws from Pattern-Oriented Software
Architecture (POSA, Buschmann et al.), Patterns of
Enterprise Application Architecture (Fowler),
Enterprise Integration Patterns (Hohpe and Woolf), and
the common distributed and cloud patterns that emerged
later.
Listing a pattern here does not recommend it. Many overlap,
some solve the same problem in different ways, and several exist
only to work around limits of a particular language. State and
State
Machine are one overlapping pair. State
changes an object’s behavior when its internal state changes.
State Machine drives an object through a known set of
states in response to inputs. State Machine builds on
State . The machine chooses each successor, so the
object advances without the client choosing. The body of this
book argues that several of the patterns written around a
language’s limits dissolve
in Python .
The tables follow each source’s own grouping, so each name
sits where its source puts it. One of those groupings is GoF’s
Creational /Structural /Behavioral
split , which Design Patterns
accepts for Creational and questions for
Structural and Behavioral . A few idioms below
belong to no single source and sit instead in three groups by
what they share: language idioms, most of them tied to C++ or
Java’s limits, functional idioms, and the patterns that supply a
collaborator from outside. Everything else sits in Other
Patterns and Idioms, whose rows share no trait. The source and
group tables list their rows alphabetically, and for the classic
patterns that is also GoF’s own order.
When this book covers a pattern, its name links to that
coverage. A name without a link leaves that pattern to the
literature.
Finding a Pattern by
Problem
The tables below group by source, so use this section’s table
when you know the problem but not the name.
Creating objects without naming their classes
Abstract Factory , Builder , Factory
Method , Prototype , Registry ,
Plugin
Controlling access to another object
Proxy
Adding behavior to an object without changing its class
Decorator
Converting one interface into another a client expects
Adapter
Simplifying access to a subsystem
Façade
Proxying a service’s calls from a helper process
Ambassador , Sidecar
Swapping an algorithm at runtime
Strategy
Encapsulating a request as an object
Command
Passing a request along a chain until something handles
it
Chain of Responsibility
Changing behavior when an object’s internal state
changes
State
Driving an object through a known set of states
State Machine
Adding an operation without changing the classes it
visits
Visitor
Resolving behavior from the runtime types of two
objects
Double Dispatch
Structuring recursive or tree-shaped data
Composite , Interpreter ,
Visitor
Keeping the number of objects down
Flyweight , Multiton , Object Pool ,
Singleton
Saving and restoring state
Memento , Event Sourcing
Reacting to change
Observer , Publish-Subscribe Channel ,
Model-View-Controller
Coordinating concurrent work
Thread Pool , Producer-Consumer ,
Future/Promise , Active Object ,
Reactor
Keeping a program running when a dependency fails
Circuit Breaker , Retry , Bulkhead ,
Timeout , Dead Letter Channel
Returning several named values from one call
Messenger , Data Transfer Object
Moving data across a boundary
Data Transfer Object , Message Translator ,
Gateway , Data Mapper
Persisting domain objects to a database
Active Record , Repository , Table
Module , Lazy Load , Unit of Work ,
Identity Map
Organizing application logic by request or use case
Transaction Script , Domain Model ,
Service Layer , Front Controller
Modeling a value, amount, or special case instead of
null
Value Object , Money , Special
Case , Null Object
Routing or transforming a message
Content-Based Router , Message Router ,
Splitter , Aggregator
Connecting an application to a messaging system
Message , Message Channel , Message
Endpoint , Point-to-Point Channel
Supplying a collaborator from outside, an application of
Inversion of Control
Dependency Injection , Service Locator ,
Strategy
Creational (GoF)
Abstract
Factory
Create families of related objects without naming concrete
classes.
Builder
Build a complex object in steps, keeping the assembly
separate from the finished object.
Factory
Method
Defer instantiation to a method so subclasses choose the
concrete type.
Prototype
Create new objects by cloning an existing instance.
Singleton
Ensure a class has one instance with a single point of
access.
Structural (GoF)
Adapter
Convert one interface into another a client expects.
Bridge
Separate an abstraction from its implementation so both vary
independently.
Composite
Treat individual objects and compositions of them uniformly
through a tree.
Decorator
Attach responsibilities to an object dynamically by wrapping
it.
Façade
Provide one simplified interface to a subsystem.
Flyweight
Share fine-grained objects to support large numbers of them
efficiently.
Proxy
Provide a surrogate that controls access to another
object.
Behavioral (GoF)
Chain
of Responsibility
Pass a request along a chain until a handler processes
it.
Command
Encapsulate a request as an object, enabling queues,
logging, and undo.
Interpreter
Represent a grammar and evaluate sentences written in
it.
Iterator
Access the elements of a collection in order without
exposing its structure.
Mediator
Route communication between objects through one place to
reduce coupling.
Memento
Capture and restore an object’s state without breaking
encapsulation.
Observer
Notify dependents automatically when an object changes
state.
State
Change an object’s behavior when its internal state
changes.
Strategy
Make a family of algorithms interchangeable at runtime.
Template
Method
Define an algorithm’s skeleton, letting subclasses fill in
steps.
Visitor
Add operations to an object structure without changing its
classes.
Concurrency (POSA and
others)
Active Object
Decouple a method call from its execution by giving the
object its own thread.
Balking
Refuse an action when the object is in an unsuitable
state.
Double-Checked
Locking
Skip the lock once a lazily initialized shared resource
exists.
Future/Promise
Represent a result that becomes available later.
Guarded Suspension
Block a call until a precondition becomes true.
Half-Sync/Half-Async
Separate synchronous and asynchronous work, joined by a
queue.
Leader/Followers
Let a pool of threads take turns receiving and handling
events.
Monitor Object
Serialize access so only one method runs on an object at a
time.
Proactor
Dispatch the completion of asynchronous operations to
handlers.
Producer-Consumer
Decouple work creation from processing through a shared
queue.
Reactor
Dispatch incoming requests to handlers synchronously as they
arrive.
Read-Write Lock
Allow concurrent readers but exclusive writers.
Thread
Pool
Reuse a set number of worker threads across many tasks.
Thread-Specific
Storage
Give each thread its own copy of a value, as
threading.local does; ContextVar
scopes the value to the context instead.
Reactor is a name that hides its job. The pattern is
a dispatcher. One loop waits on many event sources and hands
each event to the handler registered for it, and the original
description of Reactor lists Dispatcher as
another name for it. “Reactor” survives because the literature
and the libraries use it. Both asyncio’s
SelectorEventLoop and Twisted’s
reactor implement Reactor .
Proactor follows the same naming, and asyncio’s
ProactorEventLoop, the default on Windows, is
one.
Architectural (POSA)
Blackboard
Let independent components cooperate through a shared data
store.
Broker
Coordinate requests and replies between distributed
components.
Layers
Stack responsibilities so each layer uses only the one
beneath it.
Microkernel
Keep a minimal core and add capability through
plug-ins.
Model-View-Controller
(MVC)
Separate data, presentation, and input handling.
Pipes
and Filters
Process a stream through a chain of independent
transforms.
Presentation-Abstraction-Control (PAC)
Build interactive systems from cooperating agents, each
split three ways.
Reflection
Let a program inspect and adjust its own structure at
runtime.
Enterprise Application
(Fowler)
Active Record
Wrap a table row in an object that loads and saves
itself.
Data Mapper
Move data between objects and the database, so neither names
the other.
Data
Transfer Object (DTO)
Carry data between processes in one batched object.
Domain Model
Model business logic as a graph of objects.
Front Controller
Route all requests through a single handler.
Gateway
Wrap access to an external system in a simple
interface.
Identity Map
Load each object once per session.
Lazy Load
Defer loading a persisted object until something needs
it.
Money
Represent monetary amounts together with their
currency.
Plugin
Select an implementation by naming its class in
configuration rather than in code.
Registry
Keep one well-known object where the rest of the program
looks up services or data.
Repository
Stand between the domain and the data store, presenting
stored objects as a queryable collection.
Service Layer
Define an application boundary as a set of operations.
Special
Case
Supply a subclass for a special case instead of a null check
at every use.
Table Module
Let one class handle all rows of a table.
Transaction Script
Organize logic as one procedure per request.
Unit of Work
Track changes in a transaction and commit them
together.
Value
Object
Model a small value as an immutable object compared by
value, not identity.
Integration
and Messaging (Hohpe and Woolf)
Aggregator
Combine related messages into one.
Content-Based Router
Route by inspecting the message content.
Dead Letter Channel
Hold messages the messaging system cannot deliver.
Message
Package data to send over a channel.
Message Channel
Connect senders and receivers through a logical pipe.
Message Endpoint
Connect an application to the messaging system.
Message Router
Send a message to a destination chosen at runtime.
Message Translator
Convert a message from one format to another.
Point-to-Point Channel
Deliver a message to exactly one receiver.
Publish-Subscribe
Channel
Broadcast a message to every subscriber to its topic.
Splitter
Break one message into several.
Distributed and Cloud
Ambassador
Route a service’s outbound calls through a helper.
API Gateway
Offer one entry point in front of many services.
Bulkhead
Isolate resources so one failure does not stop the whole
system.
Circuit Breaker
Stop calling a failing service until it recovers.
Command Query Responsibility Segregation
(CQRS)
Separate the read model from the write model.
Event Sourcing
Store state as a log of events instead of current
values.
Retry
Re-attempt a failed operation, often with backoff.
Saga
Run a long transaction as a series of compensable
steps.
Service Discovery
Locate service instances dynamically.
Sidecar
Attach helper functionality to a service as a separate
process.
Strangler Fig
Replace a legacy system incrementally by routing around
it.
Timeout
Bound how long to wait for a response.
Language and
Implementation Idioms
Curiously Recurring Template Pattern (CRTP)
Parameterize a base class by the subclass that inherits from
it.
Marker Interface
Tag a class with an empty interface to signal a
capability.
Mixin
Add reusable behavior through multiple inheritance.
Pointer to Implementation (Pimpl)
Store a class’s implementation in a separate object reached
through a pointer, so changing the implementation does not force
clients to recompile.
Resource
Acquisition Is Initialization (RAII)
Acquire a resource in a constructor and release it in the
destructor.
Functional Idioms
Function
Composition
Build a function by passing one function’s output to the
next.
Memoization
Cache a function’s results keyed by its arguments.
Monad
Sequence computations inside a context such as optionality,
error, or async.
Partial
Application
Preset some of a function’s arguments and get a function
expecting the rest.
Dependency Supply
Dependency
Injection
Supply an object’s collaborators from outside it.
Inversion
of Control
Let a framework call your code rather than the reverse.
Dependency Injection and Service Locator each
implement Inversion of Control .
Service
Locator
Look up dependencies through a central registry.
Other Patterns and
Idioms
Borg
(Monostate)
Let every instance share one set of state instead of sharing
one instance.
Double
Dispatch
Resolve behavior from the runtime types of two objects,
through two calls.
Fluent
Interface
Return the receiver from each method so calls chain into one
expression.
Function
Object
Decouple the choice of function to call from the place that
calls it.
Lazy
Initialization
Create a value on first use.
Messenger
Bundle values into one object with named attributes; the
in-process form of Data Transfer Object .
Multiton
Manage a pool of singletons, one per key.
Null
Object
Use an object with neutral behavior in place of null.
Object
Pool
Reuse expensive objects from a managed pool.
Specification
Encapsulate a rule as a predicate that combines with
others.
State
Machine
Drive an object through a known set of states in response to
inputs.
Surrogate
Put a stand-in in front of the object that does the work;
Proxy and State are both forms of
Surrogate .
Type Object
Represent a “kind of” thing as data rather than a
subclass.
Patterns Python Absorbed
Several entries above are in the catalog because the
literature documents them, not because you need to write them.
Python includes the piece their inventors set out to supply.
Subtracting Python’s share leaves the intent, not the
structure. Each link leads to the section that subtracts
Python’s share from its pattern.
← Simulation
Foundations →