Design Patterns Glossary
A
Category: creational pattern (Gang of Four).
An interface for creating families of related objects without naming their concrete classes. A client asks the factory for a button, a checkbox and a window and gets a matching set for Windows, macOS or the web, depending on which concrete factory it was given. Java's DocumentBuilderFactory and the "theme" factories in UI toolkits are examples.
Category: enterprise pattern (Fowler, PoEAA).
An object that wraps one row of a database table, carries the data, and also knows how to load, save and delete itself: user.save(), User.find(id). Rails ActiveRecord, Django's ORM and Laravel's Eloquent follow it.
Category: concurrency pattern.
Concurrency built from actors: independent units that hold private state, receive messages through a mailbox and process them one at a time, replying or sending new messages, and creating other actors. No shared memory, so no locks. Erlang and Elixir are built on it; Akka brings it to the JVM; Orleans to .NET.
Category: structural pattern (Gang of Four).
Converts the interface of an existing class into the one a client expects, so that classes that could not work together can. An object adapter wraps an instance; a class adapter inherits from both sides (where the language allows). Java's InputStreamReader (bytes to characters) and Arrays.asList (array to List) are adapters, as is every wrapper you write around a third-party SDK.
Category: domain-driven design (Evans).
A cluster of domain objects (an Order with its OrderLines) treated as one unit for data changes, with a single entry point, the aggregate root. Outside code holds references only to the root and changes the inside only through it, so the root can enforce invariants ("an order cannot exceed the credit limit"). Each aggregate is loaded and saved as a whole by a repository and is the boundary of a transaction.
Category: anti-pattern.
Domain classes that are only data holders (getters and setters, no behaviour), with all the logic in separate "service" or "manager" classes. It looks object-oriented but is procedural code with extra indirection, and the rules about an object are spread across many services. Fowler named it in 2003.
Category: domain-driven design (Evans).
A translation layer between your model and an external or legacy system whose model is different or messy, so that its concepts do not leak into yours. Built from facades, adapters and translators that convert between the two models.
Category: fundamentals.
A commonly used solution that looks reasonable but produces more problems than it solves: a god object, a service locator hiding dependencies, copy-paste reuse, premature optimisation. The term comes from the 1998 book "AntiPatterns"; the useful part of each is the refactored solution.
B
Category: architectural pattern.
A separate backend layer per kind of client (web app, mobile app, partner API) that aggregates and shapes data from the core services for that client's needs, instead of one general-purpose API serving everyone. Each BFF is owned by the team that owns the client.
Category: anti-pattern.
A system with no recognisable architecture: everything depends on everything, logic lives wherever it was convenient, and changes in one place break unrelated features. Named in a 1997 paper by Foote and Yoder, which also observed that it is the most common architecture in practice.
Category: domain-driven design (Evans).
An explicit boundary within which a domain model and its terms have one precise meaning. "Customer" in Sales (a lead with a contact) is a different model from "Customer" in Billing (an account with invoices), and each context owns its own. Contexts talk through defined relationships: shared kernel, customer-supplier, anti-corruption layer, published language.
Category: structural pattern (Gang of Four).
Separates an abstraction from its implementation so the two can vary independently: a Shape hierarchy (circle, square) holds a reference to a Renderer hierarchy (vector, raster) instead of creating every combination as a subclass (VectorCircle, RasterCircle, ...). Composition replaces a class explosion. JDBC drivers behind the JDBC API and GUI toolkits over platform back ends are bridges.
Category: creational pattern (Gang of Four).
Constructs a complex object step by step through a separate builder object, so that the same construction process can produce different representations and the client can set only the parts it needs: new Request.Builder().url(u).header(h).post(body).build(). It solves the "telescoping constructor" problem of many optional parameters and can enforce that the object is valid before it exists. The GoF version also has a Director that drives the steps; modern use usually skips it.
C
Category: fundamentals.
A function passed to another function to be called later: when a button is clicked, when a request completes, for each element of a list. Callbacks are the simplest form of inversion of control and the mechanism under Observer, Strategy (as a lambda), Template Method hooks and asynchronous APIs. Deeply nested asynchronous callbacks ("callback hell") led to promises and async/await.
Category: behavioural pattern (Gang of Four).
Passes a request along a chain of handlers; each handler either deals with it or forwards it to the next. The sender does not know which handler will respond. Logging frameworks (levels), servlet filters, exception handling up the call stack, approval workflows and UI event bubbling all work this way; web middleware is the modern form.
Category: architectural pattern.
A resilience pattern for calls to remote services: count failures, "open" the breaker after a threshold so calls fail fast instead of hanging, and probe periodically to close it again. Described in Nygard's "Release It!" and implemented by Hystrix, resilience4j and Polly. The related patterns are Retry, Timeout and Bulkhead.
Category: anti-pattern.
Two or more modules, classes or services that depend on each other, directly or through a chain, so neither can be understood, built, tested or deployed without the other. Symptoms: import errors, DI containers failing at start-up, "temporarily" using setter injection to break the cycle, and services that cannot be released independently.
Category: architectural pattern.
A family of layered designs (Onion by Palermo, 2008; Clean Architecture by Robert C. Martin, 2012) with one rule: source code dependencies point inward. The domain entities are in the centre, use cases around them, then interface adapters (controllers, presenters, gateways), then frameworks and drivers (web, database, UI) on the outside. Inner layers define interfaces that outer layers implement, so the business rules know nothing about the database or the web framework.
Category: fundamentals.
A surface sign in code that usually points to a deeper design problem, named by Kent Beck and catalogued in Fowler's "Refactoring": long method, large class, long parameter list, duplicated code, feature envy (a method more interested in another class's data), shotgun surgery (one change touches many classes), divergent change (one class changes for many reasons), primitive obsession, data clumps, switch statements on type codes, speculative generality, comments that explain bad code.
Category: behavioural pattern (Gang of Four).
Turns a request into an object that carries everything needed to perform it (and often to undo it), so requests can be queued, logged, retried, composed into macros and undone. A text editor keeps a stack of executed commands for undo; a task queue stores commands as jobs; Redux actions and GUI menu items are commands.
Category: structural pattern (Gang of Four).
Composes objects into tree structures and lets clients treat individual objects and groups uniformly through one interface: a Graphic that is either a Line or a Picture containing Graphics; a file system of files and directories; a UI of components containing components; an expression tree. Operations recurse down the tree.
Category: principle.
Prefer building behaviour by combining objects (a Car has an Engine) to inheriting it (a Car is a Vehicle with an overridden method). Composition keeps classes small, lets behaviour change at run time, and avoids the fragile base class problem, where a change in a parent silently breaks subclasses. Inheritance remains right for true "is-a" relationships with stable, shared behaviour.
Category: principle.
A framework makes sensible decisions by default (a class named UserController handles /users, a table named users backs the User model, tests live in a test folder) so that developers configure only the unusual cases. Rails made it famous; Spring Boot, Django and most modern frameworks follow it.
Category: principle.
Coupling is how much one module depends on the internals of another; cohesion is how closely the parts of one module belong together. Good design is low coupling and high cohesion: each module does one thing well and knows little about the others. Kinds of coupling, from bad to acceptable: content (reaching into another's internals), common (shared globals), control (passing flags that steer the other's logic), data (passing just what is needed), message (only through published interfaces).
Category: architectural pattern.
Separating the model that handles commands (writes) from the model that serves queries (reads), possibly with different data stores. It generalises Bertrand Meyer's Command-Query Separation (a method should either change state or return data, not both) from methods to whole systems. Often paired with event sourcing.
Category: functional pattern.
Currying transforms a function of several arguments into a chain of single-argument functions: add(a, b) becomes add(a)(b). Partial application fixes some arguments of a function and returns a function of the rest: add5 = partial(add, 5). Both create specialised functions from general ones and are everyday tools in JavaScript, Python (functools.partial), Haskell and Scala.
D
Category: enterprise pattern (Fowler, PoEAA).
A layer that moves data between objects and the database while keeping the two independent: domain objects know nothing about SQL or tables, and the mapper does the translation. Hibernate, Doctrine, Entity Framework and SQLAlchemy's mapper are Data Mappers (usually with a Unit of Work).
Category: enterprise pattern (Fowler, PoEAA).
A plain object that carries data between processes or layers, with no behaviour: the shape of an API request or response, the object a service returns to a controller. It decouples the external contract from internal domain objects, so the domain can change without breaking clients and sensitive fields are not exposed by accident. Records, data classes and mapping libraries (MapStruct, AutoMapper) reduce the boilerplate.
Category: structural pattern (Gang of Four).
Adds behaviour to an object by wrapping it in another object with the same interface, so decorators can be stacked at run time: new BufferedReader(new InputStreamReader(new FileInputStream(f))). Each wrapper does its part and delegates to the wrapped object. Logging, caching, retrying, authorisation and compression around a service are typical decorators; Python and TypeScript "decorators" are a language feature that often, but not always, implements this pattern.
Category: creational pattern.
Giving an object its dependencies from the outside (through the constructor, a setter or an interface) instead of letting it create or look them up itself. The object depends on an abstraction; something else (the composition root, often a DI container such as Spring, Guice, Dagger, NestJS or Angular's injector) chooses the concrete implementation. It makes dependencies explicit and swappable, which is what makes unit testing with fakes possible.
Category: principle.
High-level modules should not depend on low-level modules; both should depend on abstractions, and abstractions should not depend on details. In practice: the business logic defines the interface it needs (OrderRepository), and the database code implements it, so the dependency arrow points from the infrastructure to the domain, not the other way round.
Category: fundamentals.
A named, reusable solution to a recurring design problem, described by its intent, the forces it balances, its structure and its consequences. The term comes from the architect Christopher Alexander; the 1994 book "Design Patterns: Elements of Reusable Object-Oriented Software" by Gamma, Helm, Johnson and Vlissides (the "Gang of Four", GoF) catalogued 23 patterns in three groups: creational (how objects are made), structural (how they are composed) and behavioural (how they interact). Later catalogues added enterprise, architectural, concurrency and integration patterns.
Category: domain-driven design.
An object that records something meaningful that happened in the domain, named in the past tense: OrderPlaced, PaymentFailed, UserRegistered. Aggregates raise events; other parts of the system (in the same process or in other services) react to them, which decouples the code that performs an action from the code that responds to it.
Category: enterprise pattern (Fowler, PoEAA).
An object model of the business, in which classes carry both data and the behaviour and rules that belong to that data: an Account that knows how to withdraw and when to refuse, an Order that computes its own total and validates its lines. The opposite of the anemic model and of the procedural Transaction Script.
Category: concurrency pattern.
Lazily creating a shared object exactly once in a multithreaded program: check whether it exists, and only if not, take a lock, check again, then create it. The second check avoids a race; the first check avoids taking the lock on every call. In Java it is correct only if the field is volatile (since Java 5); the initialisation-on-demand holder idiom (a nested class) and enum singletons are simpler and safe.
Category: principle.
Every piece of knowledge should have a single, authoritative representation in the system. Duplicated logic drifts: one copy gets the bug fix, the other does not. DRY is about knowledge and rules, not about identical-looking lines; two pieces of code that look the same but change for different reasons should stay separate.
E
Category: fundamentals.
Keeping an object's data and the operations on it together, and hiding the internal representation behind a public interface so that it can change without affecting callers. Information hiding (Parnas, 1972) is the design principle; encapsulation is its language mechanism (private fields, modules, closures). Getters and setters for every field are not encapsulation; they expose the representation with extra steps.
Category: domain-driven design (Evans).
A domain object defined by its identity rather than its attributes: two customers with the same name are different customers, and a customer stays the same customer when the address changes. Entities have a lifecycle and an ID; equality is by ID. Contrast with Value Objects, which are defined by their attributes.
Category: architectural pattern.
Components communicate by producing and consuming events through a broker rather than by calling each other. Producers do not know who listens; consumers can be added without changing producers. Styles range from simple notifications to event-carried state transfer and event sourcing.
Category: architectural pattern.
Storing the sequence of domain events as the source of truth and deriving current state by replaying them, instead of storing only the latest state. Gives a complete audit trail and the ability to rebuild any view, at the cost of projections for queries, event versioning and growing storage.
F
Category: structural pattern (Gang of Four).
A single, simplified interface to a complex subsystem: one PaymentFacade.charge(order) method that internally validates, calls the gateway, records the transaction and sends the receipt. Clients use the facade; the subsystem's classes remain available for those who need the detail. Facades also mark module boundaries and are natural places to put anti-corruption logic.
Category: creational pattern (Gang of Four).
Defines a method for creating an object but lets subclasses decide which class to instantiate: a Dialog base class calls createButton(), and WindowsDialog and WebDialog override it to return their own buttons, so the dialog's logic is written once against the Button interface. More loosely, any method whose job is to create objects (including static factory methods such as LocalDate.of or Integer.valueOf) is called a factory method, and the GoF meaning is often blurred with the Simple factory.
Category: principle.
Detect problems as early and as loudly as possible: validate inputs at the boundary, assert invariants, throw on invalid state instead of carrying on with bad data, fail the start-up if configuration is missing. A failure near its cause is cheap to diagnose; a failure far from it is expensive.
Category: idiom.
An API designed to read like a sentence through method chaining, where each method returns an object on which the next method can be called: query.where("age").gt(18).orderBy("name").limit(10). Named by Fowler and Evans in 2005. Builders, query builders (jOOQ, Knex, LINQ), test assertions (AssertJ, Chai) and configuration APIs use it.
Category: architectural pattern.
A front-end architecture in which state changes flow in one direction: the view dispatches actions (plain objects describing what happened), a reducer or store computes the new state from the old state and the action, and the view re-renders from the new state. Introduced by Facebook as Flux (2014) and popularised by Redux (2015); Vuex, Pinia, NgRx and Elm follow the same idea.
Category: structural pattern (Gang of Four).
Shares objects to support large numbers of fine-grained instances efficiently: the shared, immutable part (intrinsic state, e.g. a glyph's shape or a tree type's texture) lives in one flyweight object, and the varying part (extrinsic state, e.g. position) is passed in or kept outside. Java's Integer.valueOf cache and String interning, and game engines sharing meshes between thousands of objects, are flyweights.
Category: enterprise pattern (Fowler, PoEAA).
A single handler that receives every request to a web application, performs common work (authentication, logging, routing) and dispatches to the specific handler. Spring's DispatcherServlet, Rails' router, Django's URL dispatcher and Express's app object are front controllers.
Category: functional pattern.
Combining small functions into bigger ones by feeding the output of one into the next: compose(f, g)(x) = f(g(x)), or pipe(g, f) in reading order. Pipelines of map, filter and reduce, Unix pipes, and middleware chains are composition in practice. It works best with pure functions of one argument.
Category: concurrency pattern.
A placeholder for a value that will be available later. The consumer gets the future immediately, attaches continuations (then, await) or blocks on it, while the producer completes the promise when the work is done. Java's CompletableFuture, JavaScript's Promise, Python's asyncio.Future and C#'s Task implement it; async/await is syntax over it. It replaced nested callbacks and makes composing asynchronous operations (all, race, chaining, error propagation) straightforward.
G
Category: enterprise pattern (Fowler, PoEAA).
An object that encapsulates access to an external system or resource (a payment provider, a mail service, a legacy API) behind an interface shaped for your application. The rest of the code calls gateway.charge(amount) and never sees HTTP details, retries or the provider's data format; a fake gateway makes tests fast and deterministic.
Category: anti-pattern.
A class that knows or does too much: it holds most of the application's state, has hundreds of methods, and every other class depends on it. Changes anywhere ripple into it, it cannot be tested in isolation, and merge conflicts cluster around it. Often named Manager, Util, Context or Application.
Category: anti-pattern.
Using one familiar tool or pattern for every problem because it is familiar: every data store is the relational database, every service is a microservice, every variation is a Strategy. "If all you have is a hammer, everything looks like a nail."
Category: principle.
Craig Larman's nine guidelines for deciding which class should own a responsibility: Information Expert (give it to the class that has the data), Creator (the class that contains or uses the object creates it), Controller (a non-UI object receives system events), Low Coupling, High Cohesion, Polymorphism (vary behaviour by type, not by conditionals), Pure Fabrication (invent a class when no domain class fits, e.g. a Repository), Indirection (an intermediary decouples), Protected Variations (wrap what varies behind a stable interface).
H
Category: architectural pattern.
Alistair Cockburn's 2005 design: the application core (domain and use cases) is in the middle and talks to the outside world only through ports, which are interfaces the core defines. Adapters on the outside implement those ports for specific technologies: an HTTP controller or CLI drives the core through an inbound port; a PostgreSQL repository or an e-mail client is driven by the core through an outbound port. Swapping a database or adding a new interface means writing a new adapter, not touching the core.
Category: functional pattern.
A function that takes functions as arguments or returns a function: map, filter, reduce, sort with a comparator, decorators that wrap functions, event handlers registration, compose and curry. First-class functions make many object-oriented patterns (Strategy, Command, Template Method hooks, Observer) a one-liner.
I
Category: functional pattern.
Objects whose state cannot change after construction; a "change" produces a new object. Immutable objects are safe to share between threads without locks, safe to use as hash keys and cache entries, easy to reason about and to test. Java's String and records, Python's tuples and frozen dataclasses, Kotlin's val and data classes, and persistent collections in functional languages are examples; Value Objects should be immutable.
Category: fundamentals.
An interface declares a contract (method signatures, in some languages default methods) with no state; a class can implement many. An abstract class can hold state and partial implementation and is inherited by one parent chain; it is the home of Template Method. Use an interface to define a capability that unrelated classes can offer (Comparable, Serializable, Repository); use an abstract class to share implementation among closely related subclasses.
Category: principle.
Clients should not be forced to depend on methods they do not use: prefer several small, role-specific interfaces (Readable, Writable) to one large one (FileSystem with forty methods). Fat interfaces force implementers to stub methods that make no sense for them and couple unrelated clients through one type.
Category: behavioural pattern (Gang of Four).
Represents the grammar of a small language as a class hierarchy (one class per rule, forming an abstract syntax tree) and evaluates sentences by walking the tree: arithmetic expressions, boolean rule expressions, search queries, regular expressions, a specification language. Each node has an interpret(context) method.
Category: principle.
The framework or runtime calls your code, rather than your code calling the framework: you register handlers, override hooks or declare components, and the framework decides when they run. Also called the Hollywood principle ("don't call us, we'll call you"). Dependency injection containers, event loops, web frameworks calling your controllers and Template Method hooks are all forms of it.
Category: behavioural pattern (Gang of Four).
Provides sequential access to the elements of a collection without exposing its internal structure, through a small interface (hasNext/next, or a protocol of iter/next). It separates traversal from the collection, allows several simultaneous traversals, and lets lazily computed or infinite sequences be consumed element by element. Built into every modern language: Java's Iterable, Python's iterators and generators, C#'s IEnumerable, JavaScript's iteration protocol.
K
Category: principle.
Prefer the simplest design that solves the problem: fewer layers, fewer abstractions, fewer configuration options, plain code over clever code. Simplicity is measured by how easily the next person understands and changes it, not by line count alone.
L
Category: principle.
A method should talk only to its immediate collaborators: its own fields, its parameters, objects it creates, and (loosely) globals; not to the objects it gets back from them. The smell is a chain such as order.getCustomer().getAddress().getCity(), which couples the caller to three classes' structure; the fix is order.getShippingCity() or passing what is needed. Fluent interfaces and pure data structures are accepted exceptions.
Category: architectural pattern.
Organising code into horizontal layers with a fixed dependency direction: presentation (controllers, views), application or service layer, domain or business logic, and data access, each calling only the layer below (strict) or any lower layer (relaxed). The most common structure for business applications and the default in most frameworks.
Category: creational pattern.
Delaying the creation of an object or the loading of data until it is first needed: a configuration parsed on first access, a database relation loaded when first traversed. Fowler's Lazy Load variants: lazy initialisation (check for null), virtual proxy (a stand-in that loads on first use), value holder and ghost. ORMs use it for relations, which is the source of the N+1 query problem.
Category: anti-pattern.
An abstraction that fails to hide the details underneath, so users must understand them anyway: an ORM where you still need to know the SQL it generates to avoid N+1 queries, a remote procedure call that looks like a local call but fails in network ways, a file system over a network with its latency. Joel Spolsky's 2002 formulation: all non-trivial abstractions leak to some degree.
Category: principle.
Objects of a subclass must be usable wherever the parent is expected without the caller noticing: a subclass must honour the parent's contract (preconditions no stronger, postconditions no weaker, invariants kept, no new exceptions). The classic violation is Square extending Rectangle: setting the width of a "rectangle" that is secretly a square changes its height too. Another is a ReadOnlyList that extends List and throws on add().
M
Category: anti-pattern.
Unexplained literal values in code: if (status == 3), retry 7 times, a URL or a type name typed in several places. Nobody knows what 3 means, and a change must be found everywhere. The fix is a named constant, an enum or a configuration value with one definition.
Category: functional pattern.
The three basic higher-order operations on collections: map transforms each element, filter keeps the ones that satisfy a predicate, reduce (fold) combines all elements into one value. Available in every mainstream language (Java streams, JavaScript arrays, Python built-ins and comprehensions, C# LINQ, Kotlin collections) and the building blocks of data pipelines, including the distributed MapReduce model.
Category: behavioural pattern (Gang of Four).
An object that centralises how a set of components interact, so they communicate through the mediator instead of referring to each other: a dialog in which changing one field enables or disables others, an air-traffic controller between planes, a chat room between users. Components become reusable because they know only the mediator; the mediator holds the interaction logic. Libraries such as MediatR (.NET) apply it to request handling.
Category: behavioural pattern (Gang of Four).
Captures an object's internal state in a separate memento object so it can be restored later, without exposing the object's internals: the originator creates and restores mementos, a caretaker stores them (an undo stack), and nobody else can read them. Snapshots in editors, savepoints in transactions and checkpoints in games are mementos.
Category: architectural pattern.
A minimal core that provides the essential services and an extension mechanism, with the features delivered as plugins that register with the core through defined interfaces: Eclipse, VS Code, browsers and their extensions, Jenkins, and many build tools and IDEs. The core defines the contract; plugins can be developed, loaded and updated independently.
Category: architectural pattern.
An application built as a set of small, independently deployable services, each owning its data and communicating over the network. Boundaries follow bounded contexts; teams own services end to end. The trade is organisational and scaling freedom for distributed-systems complexity.
Category: architectural pattern.
A chain of functions that each receive a request, do some work (logging, authentication, parsing, rate limiting, error handling) and either pass control to the next function or end the chain with a response. Express, Koa, ASP.NET Core, Django and Rails (Rack) all structure request handling this way; gRPC interceptors and Redux middleware are the same idea elsewhere.
Category: structural pattern.
A class or module that provides methods to be included in other classes without being their parent in an "is-a" sense: Ruby modules, Python multiple inheritance with small helper classes, Scala traits, TypeScript mixin functions, Django's class-based view mixins. A way to reuse behaviour horizontally across unrelated classes.
Category: architectural pattern.
Separates an interactive application into the model (data and business logic), the view (presentation) and the controller (handles input, updates the model, selects the view). Invented by Trygve Reenskaug at Xerox PARC in 1979 for Smalltalk; the web version (Rails, Django's MTV, Spring MVC, ASP.NET MVC) maps a request to a controller action that reads or updates the model and renders a view template.
Category: architectural pattern.
A variant of MVC for GUIs in which the view is passive (it exposes methods such as showItems() and events such as onSave) and the presenter holds all presentation logic, reading the model and telling the view what to display. The view knows nothing about the model, so the presenter can be unit-tested with a mocked view. Common in classic Android, GWT and WinForms applications.
Category: architectural pattern.
A variant for frameworks with data binding (WPF, where Microsoft introduced it in 2005; Android Jetpack; Vue, Knockout and, in spirit, React with hooks): the view model exposes observable state and commands, and the view binds to them declaratively, so the view updates automatically when the view model changes and vice versa. The view model has no reference to the view.
Category: structural pattern.
Grouping related functions and state behind a small public interface with the rest private. In JavaScript it was first done with an immediately invoked function returning an object (closure-based privacy); today ES modules, Python modules, Go packages and Java modules provide it directly. The principle is the same as encapsulation at a larger grain.
Category: functional pattern.
A type that wraps a value and provides a way to chain computations on it (flatMap, bind, then) while handling some concern automatically: Optional/Maybe (absence), Result/Either (failure), Promise/Future (asynchrony), List (multiple results), IO (side effects). The chaining function unwraps, applies your function, and re-wraps, so a pipeline of such steps reads linearly instead of nesting checks.
Category: architectural pattern.
An application deployed as one unit. A well-structured monolith has clear internal modules with enforced boundaries (a modular monolith), which gives most of the design benefits of microservices without the network between them; a badly structured one is a big ball of mud. Many successful systems run as monoliths for years and extract services only where scaling or team boundaries demand it.
N
Category: behavioural pattern.
An object that implements an interface with neutral, do-nothing behaviour and is used instead of null: a NullLogger that discards messages, an empty collection instead of null, a GuestUser with no permissions. Callers no longer check for null before every use, and the "nothing" case is explicit and testable.
O
Category: creational pattern.
Keeps a set of initialised objects ready for reuse instead of creating and destroying them on demand, for objects that are expensive to create or limited in number: database connections, threads, sockets, large buffers. Clients borrow an object and return it; the pool manages size, validation and timeouts.
Category: behavioural pattern (Gang of Four).
A one-to-many dependency: when a subject changes, all registered observers are notified, without the subject knowing who they are. Event listeners in every UI framework, JavaScript's EventEmitter, RxJS and reactive streams, property change notifications in MVVM, and the Java Observable (deprecated) are observers. Push style sends the data with the notification; pull style sends only "something changed".
Category: principle.
Software entities should be open for extension but closed for modification: adding a new case (a new payment method, a new report format) should mean adding code, not editing working code. Achieved with abstractions and polymorphism: a new Strategy, a new Decorator, a new plugin, a new subclass, rather than another branch in a switch statement.
Category: functional pattern.
Types that make absence and failure explicit in the signature instead of using null and exceptions: Optional
P
Category: architectural pattern.
Processing data through a sequence of independent steps (filters), each reading from the previous step and writing to the next (pipes): Unix shell pipelines, compilers (lex, parse, optimise, emit), ETL and streaming jobs, image-processing chains, Java streams and reactive pipelines. Filters are reusable and can run in parallel; the pipeline is easy to extend by inserting a step.
Category: fundamentals.
One interface, many implementations: calling shape.area() runs circle or square code depending on the object's actual type (subtype polymorphism via virtual dispatch). Parametric polymorphism is generics (List
Category: anti-pattern.
Making code more complex for performance before measuring that it matters: caching everything, hand-written data structures, micro-optimisations in code that runs once. Knuth: "premature optimisation is the root of all evil (or at least most of it) in programming". The opposite failure is ignoring obvious algorithmic problems (an O(n²) loop over a large table) that are cheap to fix up front.
Category: principle.
Code, APIs and interfaces should behave the way their users expect: a method called getTotal() does not send an e-mail, a function named by convention does what the convention implies, and similar operations have similar names and parameter orders. Surprises cost debugging time and cause misuse.
Category: concurrency pattern.
One or more producers put work items into a shared, usually bounded, queue and one or more consumers take them out, so the two sides run at their own pace and the queue absorbs bursts. A bounded queue gives back pressure: producers block or are rejected when it is full. Java's BlockingQueue, Go channels, Python's queue.Queue and every message queue implement it.
Category: principle.
Depend on abstract types (interfaces, abstract classes, protocols) in declarations and signatures, and choose the concrete class in one place (a factory, a DI container, the composition root). Then implementations can be swapped, faked in tests and extended without changing the callers. It is the first principle in the Gang of Four book.
Category: creational pattern (Gang of Four).
Creates new objects by copying an existing one (the prototype) rather than by constructing from scratch, useful when construction is expensive or when the set of configurations is defined at run time: cloning a pre-configured document template, duplicating a game entity, JavaScript's prototype-based objects (Object.create). Deep versus shallow copy is the main implementation question.
Category: structural pattern (Gang of Four).
An object that stands in for another and controls access to it while offering the same interface: a virtual proxy that creates the expensive real object on first use, a protection proxy that checks permissions, a remote proxy that forwards calls over the network (RPC stubs), a caching proxy, a smart reference that counts uses. Hibernate's lazy-loaded entities, Spring AOP, Java's dynamic proxies and JavaScript's Proxy object are proxies.
Category: behavioural pattern.
Senders publish messages to named topics or channels on a broker and receivers subscribe to the topics they care about; neither side knows the other. Unlike Observer, there is an intermediary, delivery is usually asynchronous and often crosses process boundaries, and the broker can persist and replay messages. In-process event buses, Redis pub/sub, Kafka topics and cloud messaging services are examples.
Category: functional pattern.
A function whose result depends only on its arguments and that has no side effects: no I/O, no mutation of shared state, no dependence on time or randomness. Pure functions are trivially testable, safe to run in parallel, cacheable (memoization) and composable. Reducers in Redux, most of the standard library's string and math functions, and domain calculations should be pure.
R
Category: concurrency pattern.
A single thread waits for events (a socket is readable, a timer fired, a task completed) and dispatches each to its handler, which must not block; long operations are handed off and their completion comes back as another event. Node.js, browser JavaScript, nginx, Netty and Python's asyncio are reactors. It handles many connections with little memory, at the cost that one blocking or CPU-heavy handler stalls everything.
Category: fundamentals.
Changing the internal structure of code without changing its external behaviour, in small, tested steps: extract method, rename, move method, replace conditional with polymorphism, introduce parameter object, replace magic number with constant. Fowler's catalogue names them; tests make them safe. Most patterns are introduced into existing code by refactoring towards them rather than designed in up front.
Category: domain-driven design (Evans); enterprise pattern (Fowler, PoEAA).
An interface that makes a collection of domain objects (an aggregate type) look like an in-memory collection: findById, findByEmail, add, remove, with queries expressed in domain terms. The implementation does the persistence (SQL, an ORM, an API) and hides it. Unlike a DAO, which is table- and row-oriented, a repository is aggregate-oriented and belongs to the domain model.
S
Category: architectural pattern.
A sequence of local transactions across several services, each with a compensating action to undo it if a later step fails, coordinated by choreography (services react to events) or orchestration (a coordinator drives the steps). The alternative to distributed transactions in microservice systems.
Category: principle.
Each part of a system should address one concern (presentation, business rules, persistence, logging, security) so that it can be understood and changed on its own. Layers, modules, aspects and patterns such as Decorator and Middleware are all ways to separate concerns; mixing SQL into a UI handler is the classic violation.
Category: enterprise pattern (Fowler, PoEAA).
A layer of application services that defines the operations the application offers (placeOrder, cancelSubscription), coordinates domain objects and repositories to perform them, and owns transaction boundaries and security checks. Controllers, message handlers and scheduled jobs call it; the domain objects inside it hold the business rules. In DDD it is called the application layer.
Category: creational pattern (often considered an anti-pattern).
A global registry that components query to obtain their dependencies: locator.get(PaymentGateway). It achieves swappable implementations like dependency injection but hides the dependencies inside the class, so a reader cannot see what a class needs, tests must configure the global registry, and errors appear at run time. Mark Seemann's argument that it is an anti-pattern is widely accepted; it survives in frameworks and legacy code.
Category: architectural pattern.
A helper process deployed next to a service (same host or pod) that provides cross-cutting capabilities without changing the service: a proxy for mutual TLS, retries and metrics (service mesh), a log shipper, a configuration agent. The application and the sidecar share a lifecycle and a network namespace.
Category: creational pattern.
A method, often static, that creates and returns objects based on its arguments: ShapeFactory.create("circle"), Integer.valueOf(42), LocalDate.of(2026, 10, 27), Files.newBufferedReader(path). Not a Gang of Four pattern, but the most common factory in real code. It centralises creation logic, can hide the concrete class, return cached or shared instances, choose a subtype, and have a meaningful name.
Category: principle.
A module or class should have one reason to change, that is, it should be responsible to one actor or one concern. A class that formats reports and also saves them to disk changes when the format changes and when the storage changes; split it. Robert C. Martin's later formulation: gather together the things that change for the same reasons, separate those that change for different reasons.
Category: creational pattern (Gang of Four).
Ensures a class has exactly one instance and provides a global point of access to it: a private constructor, a static instance and a getInstance() method. Used for configuration, logging and shared caches. Thread-safe variants: eager initialisation, a synchronized accessor, double-checked locking with volatile, the initialisation-on-demand holder idiom, or a Java enum.
Category: principle.
Five object-oriented design principles collected by Robert C. Martin (the acronym was coined by Michael Feathers): Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation and Dependency Inversion. Together they aim at code that is easy to change: small cohesive units, extension without modification, safe polymorphism, narrow interfaces, and dependencies pointing at abstractions.
Category: anti-pattern.
Code with tangled control flow and no clear structure: long functions, deeply nested conditionals, goto-like jumps, global state changed from everywhere, and no boundaries between concerns. It is the small-scale version of the big ball of mud.
Category: domain-driven design (Evans and Fowler).
A business rule packaged as an object with an isSatisfiedBy(candidate) method that can be combined with and, or and not: OverdueInvoice.and(HighValue). Used for validation, for selecting objects from a collection, and for building queries from the same rules so the database and the domain agree on what "overdue" means.
Category: behavioural pattern (Gang of Four).
Lets an object change its behaviour when its internal state changes by delegating to a state object: an Order delegates pay(), ship() and cancel() to a PendingState, PaidState or ShippedState, each of which implements the allowed transitions and returns the next state. It replaces large conditionals on a status field with one class per state and makes illegal transitions impossible to write by accident.
Category: architectural pattern.
Fowler's 2004 pattern for replacing a legacy system gradually: put a facade or router in front of it, build each new piece of functionality in the new system, route the corresponding requests to it, and shrink the old system until it can be switched off. Named after the fig that grows around a tree and eventually replaces it.
Category: behavioural pattern (Gang of Four).
Defines a family of interchangeable algorithms behind one interface and lets the client choose one at run time: a Comparator passed to sort, a PaymentStrategy (card, transfer, wallet), a compression or routing algorithm. The context holds a reference to a strategy and delegates to it; new strategies are added without changing the context. In languages with lambdas, a strategy with one method is just a function parameter.
T
Category: principle.
Tell objects what to do rather than asking for their data and deciding for them: account.withdraw(amount) rather than if (account.getBalance() >= amount) account.setBalance(...). The logic that depends on an object's state belongs in that object, which keeps invariants in one place and avoids getters-and-setters code.
Category: behavioural pattern (Gang of Four).
Defines the skeleton of an algorithm in a base class method and lets subclasses override specific steps without changing the structure: an abstract DataExporter.export() that calls openFile(), writeHeader(), writeRows() and close(), with subclasses providing CSV or JSON versions of some steps. Optional steps with empty defaults are called hooks. Test frameworks' setUp and tearDown and many framework base classes use it.
Category: concurrency pattern.
A fixed or bounded set of worker threads that take tasks from a queue, so that tasks run without the cost of creating a thread each and the number of concurrent threads is capped. Java's ExecutorService, .NET's ThreadPool, Python's ThreadPoolExecutor and every web server's request handler pool are thread pools.
Category: enterprise pattern (Fowler, PoEAA).
Organising business logic as one procedure per use case (placeOrder, refundPayment) that reads from the database, applies rules and writes back, with plain data structures and little or no object model. Simple, direct and easy to understand for applications with little domain logic.
U
Category: enterprise pattern (Fowler, PoEAA).
Tracks every object loaded or changed during a business transaction and, at commit, writes all changes to the database in one go and in one database transaction, in a safe order. It avoids many small updates, keeps the in-memory objects and the database consistent, and provides an identity map so the same row is one object. Hibernate's Session, JPA's EntityManager and Entity Framework's DbContext are units of work.
V
Category: domain-driven design (Evans).
An object defined entirely by its attributes, with no identity: Money (amount and currency), Address, DateRange, EmailAddress. Two value objects with the same attributes are equal; they are immutable, replaced rather than modified, and carry behaviour such as validation and arithmetic (money.add(other) checks the currency). They replace primitive obsession (passing strings and numbers around) with meaningful types.
Category: behavioural pattern (Gang of Four).
Lets you add a new operation to a family of classes without changing them: each element class has an accept(visitor) method that calls visitor.visitCircle(this) or visitor.visitSquare(this), so the visitor's methods hold the operation for every concrete type (double dispatch). Used for operations over abstract syntax trees (type checking, code generation, pretty printing), document structures and file systems.
Y
Category: principle.
Do not build functionality or flexibility until it is actually needed: no extra configuration options, abstraction layers or extension points "just in case". From Extreme Programming. The cost of speculative generality is code that must be understood, tested and maintained for a future that often never comes, and that usually turns out to be the wrong shape when it does.
How to Use This Glossary
Each entry names the kind of pattern or principle it is (creational, structural or behavioural pattern from the Gang of Four, architectural, enterprise, domain-driven design, concurrency, functional, principle, anti-pattern, idiom or fundamentals), explains it in plain language with examples from real frameworks, and then says, under "In interviews", how to present it, which comparison the interviewer is likely to ask for, and when not to use it. Search for a term with the field at the top of the glossary; alternative names are given in the title (e.g. "Adapter (Wrapper)" or "Lazy initialization (Lazy Load)"), so searching for either one works.
If you are preparing from scratch, start with the fundamentals (Design pattern, Polymorphism, Encapsulation, Interface and abstract class), then the principles (SOLID, Composition over inheritance, Coupling and cohesion), then the ten patterns that come up most: Strategy, Observer, Factory Method, Builder, Singleton, Decorator, Adapter, Facade, Command and Template Method. The site's Design Patterns and Design Principles pages have practice problems for each.
How to Talk About a Pattern in an Interview
A pattern answer has four parts, and interviewers listen for all of them:
- The problem. What situation calls for it ("the algorithm varies by customer type and we keep adding branches").
- The structure. The participants and how they relate, in a sentence or a small diagram ("an interface, several implementations, and a context that delegates to the one it was given").
- A real example. Where you have used it or where a known framework uses it ("a Comparator passed to sort; our pricing rules per market").
- The consequences. What it costs and when you would not use it ("more classes; for one variation an if statement is clearer; in a language with lambdas a function parameter is enough").
Three habits make the difference between reciting and understanding: compare the pattern with its neighbours (Strategy with State and Template Method; Decorator with Proxy and Adapter; Observer with Mediator and Pub/sub), know the idiomatic form in your language (lambdas, records, modules, async/await often replace the class-based structure), and resist applying a pattern that the problem does not need. "I would not use a pattern here, and here is how I would introduce one if the variation appears" is a strong answer.
Choosing a Pattern
The problem in the question and the pattern it usually points to:
- Create an object with many optional parts, or validate it before it exists: Builder.
- Hide which concrete class is created, or decide it at run time: Simple factory or Factory Method; whole families of related objects: Abstract Factory.
- Exactly one instance, shared: Singleton, or better, one instance managed by dependency injection.
- Expensive or scarce objects reused: Object pool. Millions of similar objects: Flyweight. Create by copying: Prototype.
- Make an existing class fit an interface you need: Adapter. Simplify a subsystem: Facade. Wrap an external system: Gateway or Anti-corruption layer.
- Add behaviour to objects at run time, stackable: Decorator. Control access, lazy-load or cache: Proxy.
- Tree of parts and wholes treated alike: Composite. Two independent dimensions of variation: Bridge.
- Interchangeable algorithms: Strategy. Behaviour that changes with status and transitions: State. Fixed skeleton with variable steps: Template Method.
- Requests as objects, with undo, queueing or logging: Command. Snapshots for undo: Memento.
- Notify many dependants of a change: Observer; across processes or asynchronously: Publish-subscribe. Untangle many-to-many communication: Mediator.
- A request handled by one of several handlers, or by each in turn: Chain of Responsibility, Middleware.
- Add operations to a class hierarchy without changing it: Visitor. Traverse without exposing structure: Iterator. Evaluate a small language: Interpreter.
- Avoid null checks: Null Object or Optional. Reusable, combinable business rules: Specification.
- Keep business logic independent of the database and the web: Hexagonal or Clean architecture, with Repository, Data Mapper and Unit of Work.
- Persistence for simple CRUD: Active Record and Transaction Script. Rich business logic: Domain model with Entities, Value Objects and Aggregates.
- Replace a legacy system gradually: Strangler fig. Separate reads from writes at scale: CQRS. Keep history as the source of truth: Event sourcing.
- Many independent stateful things in parallel: Actor model. Work handed between fast and slow parts: Producer-consumer. Many connections, little memory: Reactor.
Where the Patterns Live in Real Code
- Java: StringBuilder and OkHttp's Request.Builder (Builder); Integer.valueOf and LocalDate.of (static factory); java.io streams (Decorator); Arrays.asList (Adapter); Collections.unmodifiableList (Proxy); Comparator (Strategy); Iterable (Iterator); Spring's DI container, AOP proxies and JdbcTemplate (Dependency Injection, Proxy, Template Method); Hibernate's Session (Unit of Work, Data Mapper, Lazy Load).
- JavaScript and TypeScript: EventEmitter and DOM events (Observer); Express and Koa middleware (Chain of Responsibility); Promises and async/await (Future); the event loop (Reactor); Redux (Command, Flux, pure reducers); Object.create (Prototype); modules and closures (Module pattern); NestJS and Angular injectors (Dependency Injection).
- Python: iterators and generators (Iterator); decorators for caching, logging and authorisation (Decorator, though a language feature); functools.partial (partial application); dataclasses(frozen=True) (Value Object, Immutability); Django's ORM (Active Record) and class-based view mixins (Mixin); asyncio (Reactor, Future).
- Frameworks in general: the request router (Front Controller); controllers, models and templates (MVC); view models with data binding (MVVM); plugin systems (Microkernel); "CustomersController handles /customers" (Convention over configuration); test fixtures' setUp and tearDown (Template Method).
Terms That Are Easy to Confuse
- Strategy vs. State: same class structure; Strategy objects are independent and chosen by the client, State objects know the transitions and replace each other.
- Strategy vs. Template Method: composition at run time vs. inheritance at compile time.
- Decorator vs. Proxy vs. Adapter: adds behaviour, same interface, stacked by the client vs. controls access, same interface, usually one vs. converts to a different interface.
- Facade vs. Adapter vs. Mediator: simplifies a subsystem vs. makes one class fit another's interface vs. coordinates peers that would otherwise talk to each other.
- Factory Method vs. Abstract Factory vs. Simple factory: creation deferred to subclasses vs. a family of related products vs. one method with a switch.
- Builder vs. Factory: step-by-step construction of one complex object vs. one call that returns a finished object.
- Observer vs. Publish-subscribe vs. Mediator: direct, synchronous, in-process vs. through a broker, asynchronous, decoupled vs. centralised interaction logic.
- Command vs. Strategy: a thing to do (with undo, queueing) vs. a way to do it.
- Composite vs. Decorator: both wrap components behind the same interface; Composite holds many children to form a tree, Decorator wraps one to add behaviour.
- Dependency Injection vs. Inversion of Control vs. Dependency Inversion Principle: a technique for supplying dependencies vs. the general principle that the framework calls you vs. the SOLID rule that dependencies point at abstractions.
- Dependency Injection vs. Service Locator: dependencies are visible in the constructor vs. hidden behind a global lookup.
- Repository vs. DAO vs. Active Record: collection of aggregates in domain terms vs. table-oriented data access object vs. the row object that saves itself.
- DTO vs. Value Object vs. Entity: data carrier across boundaries, no behaviour vs. immutable domain value with behaviour, equal by value vs. domain object with identity and a lifecycle.
- Event-driven architecture vs. Event sourcing vs. Domain Event: services communicating by events vs. events as the stored source of truth vs. the object that represents one business occurrence.
- MVC vs. MVP vs. MVVM: controller handles input and picks the view vs. presenter drives a passive view vs. view binds to an observable view model.
- Design pattern vs. idiom vs. architectural pattern: a class-level solution vs. a language-specific technique vs. a system-level structure.
- Anemic domain model vs. Transaction Script: an object model with no behaviour (usually unintended) vs. a deliberately procedural organisation of logic.
For the vocabulary of coding interviews (data structures, algorithms, complexity), see the Algorithms and Data Structures Glossary; for distributed systems and architecture at scale, the System Design Glossary; for the names and history of specific technologies, the Tech Skills Glossary for Recruiters. The basics of classes, inheritance and interfaces are covered in Object Oriented Programming (OOP).