Decorator
Definition
Decorator
- In plain English
- A decorator wraps a value that has some interface and returns a new value with the same interface plus extra behaviour.
- Think of it like
- It is like putting a phone in a waterproof case — still the same phone to use, with protection added.
Why it exists
Each payment gateway repeats logging and retry code. Fixing that repeated behaviour means editing every gateway.
A wrapper can add behaviour while keeping the same interface. You can combine several wrappers around one value.
How it works
The next field holds the wrapped value. Each wrapper satisfies the same interface and delegates the original work.
package decorators
import (
"errors"
"fmt"
)
type Gateway interface{ Charge(string, int) error }
type RealGateway struct{}
func (RealGateway) Charge(key string, cents int) error { fmt.Println(key, cents); return nil }
type Retrying struct {
next Gateway
tries int
}
func (r Retrying) Charge(key string, cents int) error {
var err error
for i := 0; i < r.tries; i++ {
err = r.next.Charge(key, cents)
if err == nil {
return nil
}
}
return err
}
func WithRetry(g Gateway, n int) (Gateway, error) {
if n < 1 {
return nil, errors.New("tries must be positive")
}
return Retrying{g, n}, nil
}
type Logging struct{ next Gateway }
func (l Logging) Charge(key string, cents int) error {
fmt.Println("charge", key)
return l.next.Charge(key, cents)
}
func Demo() {
g, err := WithRetry(RealGateway{}, 3)
if err != nil {
fmt.Println(err)
return
}
fmt.Println((Logging{g}).Charge("booking-42", 500))
}
RealGateway, Retrying and Logging satisfy Gateway; Retrying and Logging each hold another Gateway.
- Logging outside retry records one logical request. Logging inside retry records every attempt.
- Retries require a failure that may succeed later. Do not retry every payment error indiscriminately.
- The request key must identify the same payment on every attempt. The provider must prevent duplicate charges for that key.
Middleware
- In plain English
- Middleware is a decorator around a request handler, used for jobs like logging, login checks or retries.
- Think of it like
- Like the security check every visitor passes before reaching any office.
Go HTTP middleware often has the shape func(http.Handler) http.Handler. It receives a handler and returns another handler.
Examples
Wrap a payment gateway
You want logging and retries around the ferry payment gateway. Its implementation stays focused on charging.
package decorators
import (
"errors"
"fmt"
)
type Gateway interface{ Charge(string, int) error }
type RealGateway struct{}
func (RealGateway) Charge(key string, cents int) error { fmt.Println(key, cents); return nil }
type Retrying struct {
next Gateway
tries int
}
func (r Retrying) Charge(key string, cents int) error {
var err error
for i := 0; i < r.tries; i++ {
err = r.next.Charge(key, cents)
if err == nil {
return nil
}
}
return err
}
func WithRetry(g Gateway, n int) (Gateway, error) {
if n < 1 {
return nil, errors.New("tries must be positive")
}
return Retrying{g, n}, nil
}
type Logging struct{ next Gateway }
func (l Logging) Charge(key string, cents int) error {
fmt.Println("charge", key)
return l.next.Charge(key, cents)
}
func Demo() {
g, err := WithRetry(RealGateway{}, 3)
if err != nil {
fmt.Println(err)
return
}
fmt.Println((Logging{g}).Charge("booking-42", 500))
}
This stand-in always succeeds. Real retry rules must distinguish temporary failures and require provider support for the same request key.
The insight
Add behaviour by wrapping.
Cache routes for 60 seconds
Repeated route lookups can reuse a recent route. Callers still ask the same RouteStore interface.
Mutex
- In plain English
- A mutex allows only one goroutine at a time to access a protected section of code.
- Think of it like
- It is like a bathroom key that only one person can hold at a time.
package decorators
import (
"fmt"
"sync"
"time"
)
type RouteStore interface{ Route(string) string }
type RealStore struct{}
func (RealStore) Route(id string) string { return "School via Oak Street" }
type entry struct {
route string
until time.Time
}
type Cached struct {
next RouteStore
mu sync.Mutex
entries map[string]entry
}
func (c *Cached) Route(id string) string {
c.mu.Lock()
defer c.mu.Unlock()
if e, ok := c.entries[id]; ok && time.Now().Before(e.until) {
return e.route
}
route := c.next.Route(id)
if c.entries == nil {
c.entries = make(map[string]entry)
}
c.entries[id] = entry{route, time.Now().Add(60 * time.Second)}
return route
}
func Demo() {
var store RouteStore = &Cached{next: RealStore{}}
fmt.Println(store.Route("bus-7"))
fmt.Println(store.Route("bus-7"))
}
The lock protects both cache reads and writes. Holding it during lookup is safe but makes slow requests wait for each other.
The insight
Callers cannot tell a cached store from the real one.
Audit withdrawals
You must record who requested each withdrawal and how many units they requested. The wrapper records the request before delegating.
package main
import "fmt"
type Stock interface{ Withdraw(string, int) error }
type Inventory struct{}
func (Inventory) Withdraw(who string, units int) error { return nil }
type Audit struct{ next Stock }
func (a Audit) Withdraw(who string, units int) error {
fmt.Println("requested withdrawal", who, units)
err := a.next.Withdraw(who, units)
fmt.Println("withdrawal result", err)
return err
}
func main() { var s Stock = Audit{Inventory{}}; fmt.Println(s.Withdraw("Nurse Lee", 2)) }
Printing stands in for an audit record. The first entry records an attempt; the result entry distinguishes success from failure.
The insight
Shared rules such as auditing fit decorators.
Trade-offs
Pros
- Adds behaviour without editing the wrapped value.
- Small wrappers combine and test independently.
Cons
- Deep stacks complicate debugging.
- Wrapping order changes behaviour.
Use when
- Logging or auditing spans many implementations.
- Caching or safe retries belongs around an existing call.
Avoid when
- The behaviour is a core business rule.
- One direct method already reads well.
Quick check
Takeaways
- A decorator wraps a value, keeps its interface and adds behaviour.
- Stack decorators for logging, retries and caching.
- Wrapping order matters.