Patterns name recurring design decisions. They are not a requirement to create more types. Start with a concrete caller and the smallest implementation; add a boundary when it makes a real variation, invariant or ownership rule explicit.
A workflow asks a creator for an implementation, then works through the product interface. The publishing example keeps publishing independent of text versus HTML creation. A function returning an interface is often enough in Go. The payment switch in the earlier chapter is a simple factory: it centralizes selection, rather than supplying a creation step to a workflow.
Create a family of related products, not merely several unrelated objects. The furniture example keeps chair and sofa styles consistent. Add another family without changing its consumer. This costs an interface for each product role; prefer ordinary constructors when products do not need to vary together. The original vehicle factory exercise is retained beside this example for comparison.
Separate a sequence of construction steps from the result. The manufacturing director applies the same sequence to car and bike builders. It helps when construction is staged or several products share a process. A constructor or struct literal is clearer for a small record with no construction rules; a mutable builder also needs a clear policy about reuse and when the result becomes valid.
Start from a preset and produce an independent object. The shirt cache copies a prototype before customization. Its fields are values, so the copy is independent. Adding maps, slices or pointers would require an explicit deep-copy policy; a struct assignment alone would share their underlying data. For cheap objects, a normal constructor may be simpler than keeping prototypes.
Keep one process-wide identity. The counter synchronizes both creation and updates: safe initialization does not make later mutation safe by itself. Global state couples tests and callers, so tests check changes rather than an assumed initial count. Prefer passing a shared dependency explicitly when its lifetime belongs to an application or test rather than the whole process.
Translate an existing interface into one a caller expects. The
stored-message printer reuses a
legacy printer. Adapters are useful at integration boundaries; function types
with methods, such as http.HandlerFunc, are a compact Go form. Do not rename
methods behind a wrapper when the caller can simply use the original interface.
Let an abstraction and its backend vary independently. The printer example separates message formatting from output. The interface belongs to the behavior the caller needs; errors must travel back through the abstraction. If there is only one backend and no meaningful variation, a concrete writer may already provide the boundary.
Use one interface for individual elements and nested groups. The size tree calculates a total through files and directories without special treatment by the consumer. Keep it a tree: cyclic graphs need cycle handling. Go's struct embedding is a language feature, not the same pattern; a binary tree alone is not necessarily a Composite either.
Wrap an object implementing the same interface to add behavior. The
pizza layers accumulate ingredients
and propagate errors. In real Go code this often appears around io.Reader,
io.Writer or an HTTP handler. Wrapper order changes behavior, so keep ordering
visible. A function is cheaper when behavior does not need to compose.
Offer a small interface to a more involved subsystem. The weather facade owns query construction, HTTP response handling and JSON decoding. Tests replace the HTTP boundary and run offline. Convenience must still preserve failures and close response bodies. Inject a client when the application needs its own transport policy; avoid exposing every underlying option through a growing facade.
Share intrinsic data instead of allocating equivalent objects repeatedly. The team factory returns the same team for repeated requests. Treat shared objects as read-only after construction; mutating them changes what every holder sees. The cache is a sequential teaching example, not a concurrent store. Share only when reuse matters enough to justify the cache and its lifetime.
Control access while preserving the consumer-facing interface. The user proxy checks a bounded FIFO cache before the backing list. A nonpositive capacity disables caching. Its cache-hit flag belongs to the most recent lookup, including failures. The example assumes the backing data stays stable; production caches need an explicit freshness or invalidation policy and synchronization when accessed concurrently.
Give each handler the choice to stop or forward a request. The logger chain filters messages before passing them to later handlers. Forward to the next handler, not the current one. This exercise's interface has no error result; a production pipeline that needs to report write failures should use an error-returning contract. Keep chains acyclic.
Represent an operation as something that can be stored, executed and undone. The history records successful actions and keeps a failed undo available for retry. A failed command must leave its receiver in a usable state; history cannot roll back arbitrary partial side effects automatically. A callback is sufficient when there is no history, queuing or undo requirement.
Represent a small language as expressions that evaluate against a context. The boolean expressions compose variables, conjunction, disjunction and negation. Missing variables evaluate to false; short-circuiting follows boolean evaluation. This is an expression tree, not a text parser. Larger grammars warrant a parser and a separate validation phase.
Expose traversal while keeping the current position inside an object. The
generic slice iterator captures a
shallow slice snapshot and returns an explicit exhaustion result. Copying the
slice separates element storage, not objects referenced by its elements. In Go,
prefer range over a collection when a separate iterator adds no useful control.
Route interactions through a coordinator so participants do not hold references to every other participant. The named message mediator validates registration and delivery and supports synchronous replies. It is not a durable message queue and does not start goroutines. Keep domain rules out of an ever-growing central object; direct calls are clearer for a few simple peers.
Capture state without exposing its representation to the caretaker. The editor returns an opaque immutable text snapshot and restores it later. Snapshotting strings is cheap and independent; larger mutable graphs need an explicit copying and retention policy. If callers already own a small immutable value, storing that value may be enough.
Allow subscribers to react to a publisher without hard-coding them into it. The event publisher delivers synchronously in registration order using a subscription snapshot. Changes during delivery affect later publications; callbacks may publish again. Slow callbacks delay the publisher. This is sequential code, so concurrent callers must coordinate externally; asynchronous delivery would need backpressure and shutdown rules of its own.
Delegate behavior to the current lifecycle phase and enforce legal transitions. The order example makes invalid actions return errors without changing the phase. Strategy selects an algorithm; State also controls which actions make sense next. A small explicit switch can be clearer than several state types for a tiny fixed lifecycle.
Choose an algorithm behind a stable contract. The text and image printers use caller-owned writers. The caller opens and closes files; a strategy renders into the supplied writer and returns failures. The CLI connects selection to resource ownership. A function value can replace a one-method interface when it keeps the caller simpler. Algorithm selection alone does not require a factory hierarchy.
Keep a sequence fixed while allowing individual steps to vary. The
line importer owns scanning order
and delegates transformation and storage through hooks. It stops on errors;
already stored records are not a transaction and are not rolled back. It uses
bufio.Scanner's default token limit. Go can express the pattern with functions
instead of inheritance and protected methods.
Keep operations outside a set of node types while dispatching by concrete node. The file-tree visitor accumulates file sizes while traversal visits a hierarchy. New operations are convenient; a new node type requires updating the visitor interface and its implementations. Use an ordinary method or type switch when the number of operations is small.
The catalog demonstrates design choices, not a production framework. Unless a type says otherwise, serialize access to mutable instances. Callbacks and dependencies must satisfy their documented contracts. Examples do not add generic retry loops, recovery from arbitrary callback panics, distributed transactions or cycle detection to every tree. Add those only when an actual caller needs them and test the resulting contract.