Skip to content
Tutorials Center
My learning

Topics

Lesson 126 of 147 ยท Advanced Go

Design Patterns and Idioms in Go

See classic design patterns the Go way - functional options, strategy, observer with channels, factory, decorator and middleware, singleton with sync.Once, adapter, dependency injection and Go proverbs.

Design patterns are named solutions to problems that keep coming back. The famous catalog from the 1990s was written for languages built around classes and inheritance, so a literal translation into Go often looks silly: Go has no classes, no inheritance and no constructors. But the problems are real, and Go solves them with its own small toolkit: first-class functions, small interfaces, struct embedding, channels and the zero value.

This lesson walks through the patterns you will actually meet in Go code. For each one you get the problem, the idiomatic Go solution and a runnable example. Nothing needs a framework. If the building blocks are unfamiliar, review interfaces, closures and embedding first.

Functional options

Problem: a constructor with many optional settings. Go has no default parameters or overloading, and a function with ten arguments is unreadable.

Solution: accept a variadic list of option functions that each modify the object being built. You met this in constructors and options; here it is as a pattern:

Go Functional options for a server

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Callers write only what they care about, and new options can be added without breaking anyone. When there are just two or three settings, a plain config struct (Config{Timeout: 5 * time.Second}) is simpler and just as idiomatic.

Strategy: pass behavior, not a class hierarchy

Problem: choose an algorithm at run time (how to sort, how to discount a price, how to retry).

Solution: if the behavior is one operation, use a function type. If it carries state or several methods, use an interface. The standard library does both: sort.Slice takes a function, http.Handler is an interface (and http.HandlerFunc adapts a function to it).

Go Strategy with a function type and with an interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The prices are 80, 60 and 0. The three sorters print main.ByLength [fig pear kiwi banana], main.Alphabetical [banana fig kiwi pear] and main.Alphabetical [pear kiwi fig banana]. Notice what is missing: no Strategy base class, no registration. Anything with the right shape plugs in, which is the power of implicit interfaces.

Factory: a function that returns an interface

Problem: create one of several related types depending on input, without callers knowing the concrete type.

Solution: a plain function (conventionally NewX or ForX) that returns an interface. Go has no need for a factory class:

Go A factory with a registry

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

A map from name to constructor function is the standard way to build a plug-in style registry (database/sql drivers and image decoders register themselves like this). The output lists bullets, csv and numbered in that order and ends with unknown formatter "xml" (try one of [bullets csv numbered]).

Decorator and middleware

Problem: add behavior around an existing operation (logging, timing, retries, authentication, caching) without changing it.

Solution: write a function that takes something and returns something of the same type, wrapped. Chained together, these become middleware, the backbone of every Go HTTP stack (handlers and middleware).

Go Decorators and a middleware chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The result is HELLO GOPHER, logged once on the way in and once on the way out, while the flaky handler was tried three times. Order matters: Logging is outermost, so it sees the final answer; Upper wraps Retry, and Retry wraps the real handler. If Upper sat inside Retry, the error text would be upper-cased before Retry checked its prefix, and Retry would never notice the failure. Because decorators have the same type as what they wrap, they stack in any order. The same shape works for http.Handler, io.Reader (bufio.NewReader(gzip.NewReader(file))) and database drivers.

Observer: publish and subscribe with channels

Problem: several parts of a program want to react to an event, and the sender should not know who they are.

Solution: each subscriber owns a channel and a goroutine; the publisher sends the event to every channel. In Go, the callback list from classic Observer becomes a list of channels:

Go An event bus built on channels

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Each subscriber sees both events in order, in its own slice, so the output is deterministic even though the goroutines run concurrently. Design questions you must answer in a real bus: what happens when a subscriber is slow (block, drop, or buffer more?), who closes the channels (the publisher, once, as here), and how a subscriber unsubscribes. For one-to-one notification a plain channel or context cancellation is enough (concurrency patterns).

Singleton with sync.Once

Problem: exactly one shared instance (a configuration, a connection pool, a logger), created on first use.

Solution: a package-level variable guarded by sync.Once, which is safe when many goroutines ask at the same moment (the sync package):

Go A lazy, thread-safe singleton

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The instance is created once, and the settings loader prints its message once even though getSettings() is called twice. Be careful with singletons: global state makes code hard to test and to reason about. Often a better answer is to build one value in main and pass it to whoever needs it, which is the next pattern.

Adapter

Problem: you have a type with one shape and a consumer that expects another.

Solution: write a small wrapper type or function. The standard library has several: http.HandlerFunc turns a function into a Handler, and sort.Reverse wraps a sort.Interface. Adapting between your own types is a few lines:

Go Adapting a function to an interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The first call prints the SMS line and <nil>, the second returns the error notify bob: invalid phone number, and the function adapter writes to the console. The calling code depends on Notifier only, which leads to the next pattern.

Dependency injection without a framework

Problem: a component needs collaborators (a database, a clock, an email sender) but should not create them itself, so that tests can substitute fakes.

Solution: declare what you need as small interfaces, take them in the constructor and wire everything in main. There is no container and no reflection; the "framework" is the call stack:

Go Constructor injection and a fake

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Because SignupService depends only on three tiny interfaces, the test needs no database and no SMTP server, and the date is fixed so the output never changes. Define interfaces where they are used (the consumer), keep them to one or two methods, and return concrete types from constructors (designing with interfaces). Tools such as wire and fx automate the wiring in huge applications; most projects never need them.

Other idioms that appear everywhere

  • Make the zero value useful. sync.Mutex, bytes.Buffer and strings.Builder work without a constructor (make and new).
  • Accept interfaces, return structs. Parameters stay flexible, results stay concrete and documented.
  • Errors are values. Wrap with context, compare with errors.Is (error handling patterns).
  • Pipeline and fan-out/fan-in for concurrent stages, and worker pools for bounded parallelism (concurrency patterns).
  • Iterator functions replace Iterator classes (iterators).
  • Embedding instead of inheritance: delegate by embedding a type and override by defining a method (embedding).
  • Guard clauses and early returns keep the happy path unindented.
  • Table-driven tests (table-driven tests).

Patterns you rarely need

Visitor, abstract factory, builder hierarchies and deep inheritance diagrams mostly disappear in Go: type switches replace visitors, struct literals and options replace builders, and small interfaces replace class hierarchies. If you notice yourself recreating a pattern with three layers of types to get what other languages get from a class, step back and use a function or a struct.

Go proverbs

Rob Pike's proverbs, collected from his talks, summarize the style. Read them as advice about trade-offs, not commandments:

  • Don't communicate by sharing memory, share memory by communicating.
  • Concurrency is not parallelism.
  • Channels orchestrate; mutexes serialize.
  • The bigger the interface, the weaker the abstraction.
  • Make the zero value useful.
  • interface{} says nothing.
  • Gofmt's style is no one's favorite, yet gofmt is everyone's favorite.
  • A little copying is better than a little dependency.
  • Clear is better than clever.
  • Errors are values.
  • Don't just check errors, handle them gracefully.
  • Design the architecture, name the components, document the details.
  • Documentation is for users.
  • Don't panic.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main advantage of functional options over a constructor with many parameters?

    Defaults live in the constructor, options override them, and adding another Option function never changes the signature of NewServer.
  2. 2. Given h := Chain(base, A, B) where Chain wraps so the first middleware is outermost, which runs first when h is called?

    A wraps B, which wraps base. The call enters A first, then B, then base, and returns in the opposite order.
  3. 3. How is the Observer pattern usually expressed in Go?

    A channel per subscriber replaces the list of callback objects. The design questions are buffering, who closes, and unsubscribing.
  4. 4. What does sync.Once.Do(f) guarantee when 10 goroutines call it at once?

    Once makes the first call run f, blocks the other callers until f returns, and never runs it again, so everyone sees the initialized value.
  5. 5. In Go dependency injection, where should the small interface that describes a dependency usually be declared?

    Interfaces are satisfied implicitly, so the consumer can declare exactly the methods it needs. That keeps interfaces small and implementers unaware of them.

Summary

  • Go replaces most classic patterns with functions, small interfaces, embedding and channels; no framework or class hierarchy needed.
  • Functional options configure constructors; strategy is a function type or a small interface; factories are functions (often backed by a map registry).
  • Decorators and middleware are functions from a type to the same type, so they stack freely.
  • Observer uses one channel per subscriber; singleton uses sync.Once or sync.OnceValue, but passing a value from main is usually better.
  • Adapters wrap one shape into another (http.HandlerFunc is the model); dependency injection is just constructor parameters of small consumer-defined interfaces.
  • When in doubt, follow the proverbs: clear over clever, small interfaces, useful zero values, errors as values.

Next: Go Compared with Other Languages puts Go's design choices next to Java, C++, Python, Rust and Node.js.