Decorator
A decorator wraps a value of an interface and implements the same interface, adding behaviour before or after forwarding. Logging, retries, and metrics around a Store or http.RoundTripper are decorators.
Detailed Explanation
You have a Store. You want logs without editing the SQL type. type loggingStore struct { inner Store } with Find that logs and calls inner.Find is a decorator. The caller still depends on Store. You can stack decorators: logging(retry(sqlStore)).
Same interface in and out. That is the difference from an adapter, which changes the interface. A decorator preserves it. Middleware is a decorator on http.Handler. http.RoundTripper wrappers (otelhttp, logging transports) are decorators on the transport interface.
Pointer vs value. The decorator struct is usually small (the inner handle plus config). Pointer receivers are fine. Embedding the inner interface and overriding one method decorates only that method; the rest go straight to inner. That is useful and surprising. Explicit methods for every operation you care about are clearer.
What it costs. An extra call and a small struct per layer. Keep decorators orthogonal (one concern each) so you can stack them. A decorator that changes return values in a surprising way is no longer a decorator; it is a different implementation.
Code Examples
package main
import (
"context"
"log"
)
type Store interface {
Find(ctx context.Context, id string) (string, error)
}
type loggingStore struct{ inner Store }
func (s loggingStore) Find(ctx context.Context, id string) (string, error) {
v, err := s.inner.Find(ctx, id)
log.Println("find", id, err)
return v, err
}
func withLog(inner Store) Store { return loggingStore{inner: inner} }
type mem struct{}
func (mem) Find(context.Context, string) (string, error) { return "u", nil }
func main() {
var s Store = withLog(mem{})
_, _ = s.Find(context.Background(), "1")
}Common Gotchas
Embedding the inner interface and overriding one method leaves the others undecorated
usually what you want for `RoundTrip` only; document it.
This is not Python's `@decorator` syntax
it is a wrapping struct or function.
A retry decorator must not retry non-idempotent writes blindly
A retry decorator must not retry non-idempotent writes blindly