Chapter 39
Pattern Catalog
In This Chapter
This chapter gathers patterns that are widely documented
across the literature, not only the original Design
Patterns (GoF) set. It draws from Pattern-Oriented
Software Architecture (POSA), Patterns of Enterprise
Application Architecture (Fowler), Enterprise
Integration Patterns (Hohpe and Woolf), and the common
distributed and cloud patterns that emerged later.
Each entry has a one-line intent so you can recognize a
pattern by name and find it elsewhere. Listing a pattern here is
not a recommendation. Many overlap, some compete, and several
exist only to work around limits of a particular language. The
body of this book argues that a number of them are unnecessary
in Python. When this book covers a pattern, its name links to
that coverage. An unlinked name means the pattern appears only
in this catalog.
Creational (GoF)
Abstract
Factory
Create families of related objects without naming concrete
classes.
Builder
Separate constructing a complex object from its
representation, building it in steps.
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.
Monitor Object
Serialize access so only one method runs on an object at a
time.
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.
Thread
Pool
Reuse a fixed set of worker threads across many tasks.
Reactor
Dispatch incoming requests to handlers synchronously as they
arrive.
Proactor
Dispatch the completion of asynchronous operations to
handlers.
Producer-Consumer
Decouple work creation from processing through a shared
queue.
Read-Write Lock
Allow concurrent readers but exclusive writers.
Double-Checked Locking
Cut locking cost when lazily initializing a shared
resource.
Guarded Suspension
Block a call until a precondition becomes true.
Balking
Refuse an action when the object is not in a suitable
state.
Future /
Promise
Represent a result that will become available later.
Thread-Specific Storage
Give each thread its own copy of a value.
Architectural (POSA)
Layers
Stack responsibilities so each layer uses only the one
beneath it.
Pipes and
Filters
Process a stream through a chain of independent
transforms.
Blackboard
Let independent components cooperate through a shared data
store.
Broker
Coordinate requests and replies between distributed
components.
Model-View-Controller
Separate data, presentation, and input handling.
Presentation-Abstraction-Control
Build interactive systems from cooperating agents, each
split three ways.
Microkernel
Keep a minimal core and add capability through
plug-ins.
Reflection
Let a program inspect and adjust its own structure at
runtime.
Enterprise Application
(Fowler)
Domain Model
Model business logic as a graph of objects.
Transaction Script
Organize logic as one procedure per request.
Table Module
Let one class handle all rows of a table.
Active Record
Wrap a table row in an object that carries its own
persistence.
Data Mapper
Move data between objects and the database, keeping each
unaware of the other.
Repository
Mediate the domain and data with a collection-like query
interface.
Unit of Work
Track changes in a transaction and commit them
together.
Identity Map
Load each object only once per session.
Lazy Load
Defer loading data until it is actually needed.
Data Transfer
Object
Carry data between processes in one batched object.
Value
Object
A small immutable object compared by value, not
identity.
Service Layer
Define an application boundary as a set of operations.
Gateway
Wrap access to an external system behind a simple
interface.
Front Controller
Funnel all requests through a single handler.
Money
Represent monetary amounts together with their
currency.
Special
Case
Supply a subclass for a special case instead of scattering
null checks.
Registry
A well-known object others use to find services or
data.
Plugin
Choose behavior with classes named at configuration
time.
Integration
and Messaging (Hohpe and Woolf)
Message Channel
Connect senders and receivers through a logical pipe.
Message
A packet of data sent over a channel.
Publish-Subscribe
Channel
Broadcast a message to every interested subscriber.
Point-to-Point Channel
Deliver a message to exactly one receiver.
Message Router
Send a message to a destination chosen at runtime.
Content-Based Router
Route by inspecting the message content.
Message Translator
Convert a message from one format to another.
Message Endpoint
Connect an application to the messaging system.
Aggregator
Combine related messages into one.
Splitter
Break one message into several.
Dead Letter Channel
Hold messages that cannot be delivered or processed.
Distributed and Cloud
Circuit Breaker
Stop calling a failing service until it recovers.
Retry
Re-attempt a failed operation, often with backoff.
Bulkhead
Isolate resources so one failure does not sink the whole
system.
Timeout
Bound how long to wait for a response.
Saga
Run a long transaction as a series of compensable
steps.
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.
Sidecar
Attach helper functionality to a service as a separate
process.
Ambassador
Proxy a service’s outbound calls through a helper.
Strangler Fig
Replace a legacy system incrementally by routing around
it.
Service Discovery
Locate service instances dynamically.
API Gateway
Offer one entry point in front of many services.
Foundational Idioms
Null
Object
Use an object with neutral behavior in place of null.
Object
Pool
Reuse expensive objects from a managed pool.
Multiton
Manage a fixed set of named singletons.
Dependency
Injection
Supply an object’s collaborators from outside it.
Inversion of
Control
Let a framework call your code rather than the reverse.
Service Locator
Look up dependencies through a central registry.
Resource Acquisition Is
Initialization (RAII)
Tie a resource’s lifetime to an object’s scope.
Type Object
Represent a “kind of” thing as data rather than a
subclass.
Specification
Encapsulate a rule as a predicate that combines with
others.
Fluent Interface
Chain method calls that return the receiver for readable
APIs.
Mixin
Add reusable behavior through multiple inheritance.
Monad
Sequence computations inside a context such as optionality,
error, or async.
Function Object
An object whose sole purpose is to wrap a single
function.
Memoization
Cache a function’s results keyed by its arguments.
Lazy
Initialization
Create a value on first use.
Marker Interface
Tag a class with an empty interface to signal a
capability.
Curiously Recurring Template Pattern (CRTP)
A class inherits from a base parameterized by the class
itself.
Pointer to Implementation (Pimpl)
Hide a class’s implementation behind an indirection to cut
compile coupling.
← Simulation
Foundations →