Structural Patterns: Facade, Adapter, Composite, Proxy, Decorator, Bridge, Flyweight
"Structural patterns are concerned with how classes and objects are composed to form larger structures." — Gamma, Helm, Johnson, Vlissides, Design Patterns: Elements of Reusable Object-Oriented Software, Chapter 4 (1994)
Summary: The seven GoF structural patterns are seven ways to put one object in front of, around, or beside another: to simplify (Facade), to translate (Adapter), to treat a tree as one thing (Composite), to guard (Proxy), to add a layer (Decorator), to split two dimensions (Bridge) and to share (Flyweight). Focus: Intent, problem, structure, participants, consequences and the "when not to" for each pattern; the exact differences between Adapter, Bridge, Decorator, Proxy and Facade; Go's io wrappers, http.Handler middleware and httputil.ReverseProxy; Laravel's static-proxy facades, Container::extend, cache and Flysystem adapters, notification channels and PHP 8.4 lazy objects; the same ideas at service scale (API gateway, anti-corruption layer, sidecar, retry and circuit-breaker decorators). Learning goal: Look at a wrapper in real code, name which of the seven it is (or which two it combines), explain what it costs in allocations, identity and debuggability, and build the two production shapes you will meet most: a decorator chain around an HTTP client and an anti-corruption layer around a legacy API.
This page is the complete reference for the structural family of the Gang of Four catalogue. The origin of patterns and the three families are on Design Patterns: Introduction; the object-creation patterns (Factory Method, Builder, Singleton…) are on Creational Patterns; Chain of Responsibility, Strategy and Observer, which some of these wrappers resemble, are on Behavioral Patterns; combining patterns and over-patterning are on Patterns in Practice. Composition itself, and why "talk only to your friends" matters, is on Composing Objects & the Law of Demeter. The SOLID pages explain why these patterns work: Open–Closed (add behaviour without editing), Liskov Substitution (a wrapper must honour the contract it wraps), Interface Segregation (small interfaces are easy to wrap) and Dependency Inversion (adapters implement the port the core owns).
Page map
| If you are looking for | Go to |
|---|---|
| All seven patterns in three tables | Everything in one minute |
| Why composition-based structure exists at all | Why structural patterns exist |
| GoF 1994, the chapter's own comparisons, later history | Where it comes from |
| One pattern in depth (intent, structure, code, consequences) | Facade, Adapter, Composite, Proxy, Decorator, Bridge, Flyweight |
| Adapter vs Bridge vs Decorator vs Proxy vs Facade | Telling the wrappers apart |
| Java, .NET, TypeScript, Python equivalents | Per-language view |
Lost interfaces, wrapper order, Unwrap, __callStatic, extend, benchmarks | Mechanics |
| Go stdlib and Laravel framework maps | Go, Laravel |
| Vendor lock-in, cross-cutting concerns, N+1, class explosion | Solving the classic problems |
| Which pattern for which situation | Choosing |
| API gateway, ACL, sidecar, caching proxies | In architecture |
| Decorator chain and ACL labs | Lab |
| Wrong beliefs, cheat sheet, self-check, every term | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The seven, in plain words. Every row is unpacked in the patterns section.
| Pattern | In plain words | GoF intent (short) | Go example | Laravel / PHP example |
|---|---|---|---|---|
| Facade | One simple door into a complicated room | "unified interface to a set of interfaces in a subsystem" | http.Get in front of Client, Transport, Request | A CheckoutService in front of inventory, payment, shipping |
| Adapter | A plug converter | "Convert the interface of a class into another interface clients expect" | http.HandlerFunc; a struct that makes a vendor SDK satisfy your interface | Flysystem adapters, cache stores, LegacySmsAdapter |
| Composite | A folder that answers like a file | "treat individual objects and compositions of objects uniformly" | File tree, AST, io.MultiWriter (one writer made of many) | Menu tree, a rule object made of rules |
| Proxy | A stand-in that decides whether to call the real thing | "surrogate or placeholder for another object to control access to it" | httputil.ReverseProxy, caching wrapper, sync.OnceValues lazy init | Laravel's facades ("static proxies"), PHP 8.4 lazy proxies, caching repositories |
| Decorator | A layer that adds one job and passes the call on | "Attach additional responsibilities to an object dynamically" | bufio.NewWriter(gzip.NewWriter(f)), http.Handler middleware | HTTP middleware, Container::extend, Guzzle middleware |
| Bridge | Two independent dials instead of one dial per combination | "Decouple an abstraction from its implementation so that the two can vary independently" | database/sql (API) × driver.Driver (implementation) | Notification × channel, Storage API × Flysystem adapter |
| Flyweight | Share the heavy, identical part; pass the rest in | "Use sharing to support large numbers of fine-grained objects efficiently" | unique.Make (interning), a map of shared styles | Enum cases (singleton objects), a static style pool |
The wrapper family at a glance. Five of the seven wrap something. These four questions tell them apart (the long version is Telling the wrappers apart).
| Question | Facade | Adapter | Proxy | Decorator | Bridge |
|---|---|---|---|---|---|
| Does the client see a different interface than the wrapped thing? | Yes, a new simpler one | Yes, the one the client already expects | No, identical | No, identical | The abstraction's own interface |
| How many objects behind it? | Many (a subsystem) | Usually one | One subject | One component (which may itself be wrapped) | One implementor |
| Meant to be stacked? | No | Rarely | Rarely | Yes, that is the point | No |
| Designed when? | Any time | After the fact, to fit existing code | Any time | Any time | Up front, before the hierarchies grow |
Where you already use them.
| Level | Go | Laravel / PHP |
|---|---|---|
| Standard library | io, bufio, compress/gzip, net/http, httputil, database/sql, unique | Illuminate\Support\Facades, Illuminate\Container, Illuminate\Http\Client, Flysystem, PSR-7/15/18 |
| Your code | Ports and adapters, middleware, decorators around clients | Service classes, middleware, extend, custom cache/filesystem drivers, notification channels |
| Between services | Reverse proxy, API gateway, sidecar (Envoy), anti-corruption layer | The same, with Laravel as one of the services |
Why structural patterns exist
Most real code does not fail because one class is wrong. It fails because classes are connected wrongly: a controller that knows eleven classes in a payment SDK, a vendor type that leaks into every module, a subclass for every combination of features, a tree walked with if ($node instanceof Folder) in thirty places, a million objects that each carry the same 4 KiB of data. Structural patterns are the catalogue of good connections. They all use the same two mechanisms, GoF says: inheritance for class patterns and object composition for object patterns. In Go there is no inheritance, so every structural pattern in Go is the object (composition) form.
| Inheritance-based structure | Composition-based structure |
|---|---|
| Fixed at compile time | Can be rearranged at run time ("change the composition at run-time, which is impossible with static class composition", GoF) |
| One subclass per combination of features | One small type per feature, combined freely |
| Child sees parent internals (white-box reuse) | Wrapper sees only the interface (black-box reuse) |
| Fewer objects, one direct call | More objects, one forwarding call per layer |
| Easy to read in one file | The behaviour is spread over the chain; you must know the wiring |
| Not available in Go | The only option in Go: interfaces + structs + embedding |
The picture is the shortest decision procedure on this page: first ask whether the wrapper changes the interface, then whether it covers a subsystem or one object, then whether it adds behaviour or controls access. Bridge sits apart because it is a split you design before the code exists, not a wrapper you add later.
The analogy we reuse on this page: a hotel stay abroad. The concierge books your taxi, table and tickets with one request: a Facade over a city of services. The plug converter in your bag makes your laptop charger fit the wall: an Adapter. Your room key card stands in for the room and checks who you are: a Proxy. Your phone in a battery case in a waterproof pouch is still a phone, with two extra layers: Decorators. The hotel answers "how many guests?" the same way for one room, one floor or the whole building: a Composite. The remote control works with any TV that speaks the same infrared protocol, and the TV maker never designed the remote: a Bridge (remote × TV). And the hotel prints one city map design for 10,000 guests and only marks each guest's room number on it: a Flyweight.
Three common misunderstandings, up front
- "Laravel facades are the Facade pattern." Laravel's own docs call them "static proxies" to container bindings.
Cache::get()does not simplify a subsystem; it forwards one call to one object. It is a Proxy (plus a Service Locator). A GoF Facade is a class you write in front of several classes. See Laravel facades are static proxies. - "Decorator, Proxy and Adapter are the same thing: a wrapper." They share a structure, and GoF's own discussion says the similarity "belie[s] the different intents". Adapter changes the interface; Decorator keeps it and adds behaviour, meant to stack; Proxy keeps it and controls access to one subject. The intent decides the name, because the intent decides what the next developer may safely change.
- "Structural patterns are about performance." Only Flyweight is. The others cost a little (one extra call, sometimes one allocation per wrap) and pay in changeability. If a profile says a wrapper is hot, measure it; the benchmarks below show a five-layer Go decorator chain costing a few nanoseconds per call.
Where it comes from
1994, the GoF book. Chapter 4 of Design Patterns (Gamma, Helm, Johnson, Vlissides) lists seven structural patterns in alphabetical order: Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy. It splits them into class patterns, which "use inheritance to compose interfaces or implementations" (only the class form of Adapter), and object patterns, which "describe ways to compose objects to realize new functionality". The seven intents, verbatim, are the "Definition" lines in the patterns section.
The chapter closes with a discussion that is still the best way to tell the patterns apart. On Adapter and Bridge:
"The Adapter pattern makes things work after they're designed; Bridge makes them work before they are." — GoF, Design Patterns, Discussion of Structural Patterns
On Facade vs Adapter, it says a facade "defines a new interface, whereas an adapter reuses an old interface". On Decorator vs Proxy: "In the Proxy pattern, the subject defines the key functionality, and the proxy provides (or refuses) access to it. In Decorator, the component provides only part of the functionality, and one or more decorators furnish the rest." And on Composite vs Decorator: "From the point of view of the Decorator pattern, a composite is a ConcreteComponent. From the point of view of the Composite pattern, a decorator is a Leaf."
2000s–2010s, the patterns move into infrastructure. The same shapes appear at network scale. Eric Evans's Domain-Driven Design names the anti-corruption layer; Microsoft's Azure Architecture Center describes it as "a facade or adapter layer between different subsystems that don't share the same semantics". Reverse proxies, API gateways ("Gateway routing. You can use an API gateway as a reverse proxy…", Azure Architecture Center) and the sidecar ("Like a motorcycle sidecar, these components attach to a parent application and share its life cycle") are Proxy and Decorator with a network in between. Envoy describes itself as "an L7 proxy and communication bus" with an "out of process architecture".
Go. The io.Reader/io.Writer pair made Decorator the normal way to build I/O: bufio "wraps an io.Reader or io.Writer object, creating another object (Reader or Writer) that also implements the interface". net/http made the function adapter famous: "The HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers." Go 1.20 added httputil.ProxyRequest and the Rewrite hook (the older Director is now marked "Deprecated: Use Rewrite instead") and http.ResponseController, which needs wrappers to expose an Unwrap method. Go 1.21 added sync.OnceValues, a ready-made virtual proxy for initialisation. Go 1.23 added the unique package for "canonicalizing ("interning") comparable values", a standard-library Flyweight.
PHP and Laravel. PSR-7 (HTTP messages, immutable: "all methods that might change state MUST be implemented such that they retain the internal state of the current message"), PSR-15 (server middleware) and PSR-18 (HTTP client) made Adapter and Decorator interoperable across frameworks. Laravel's docs define its facades as "static proxies" to container services and describe the HTTP client as "powered by Guzzle", whose middleware "is implemented as a higher order function". PHP 8.4 added native lazy objects: "Two lazy object strategies are supported: Ghost Objects and Virtual Proxies". PHP enums (since PHP 8.1) are a built-in flyweight: "each case is backed by a singleton object of that name".
The patterns, one by one
Each block follows the same order: plain words, the usual wrong belief, GoF's definition, the problem, the structure as a picture and a participants table, a call sequence, real scenarios, Go code, Laravel code, consequences and when not to use it.
Facade Must-know
In plain words: one class with a few clear methods in front of many classes that must be called in the right order. The concierge.
Common misunderstanding: "A facade hides the subsystem; nobody may use it directly." GoF says the opposite: a facade does not prevent "applications from using subsystem classes if they need to". It is a convenience and a boundary, not a wall. If you need a wall, put the subsystem in an internal/ package (Go) or a module with a narrow public API.
Definition (GoF intent): "Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use."
Problem: checkout needs to reserve stock, authorise a payment, create a shipping label, and undo the reservation if payment fails. Without a facade, every controller, job and CLI command repeats that order and that compensation, and every one of them imports three subsystems.
| Participant | Role | In the snippet |
|---|---|---|
| Facade | Knows which subsystem classes handle a request; delegates | Checkout / CheckoutFacade |
| Subsystem classes | Do the real work; do not know the facade exists | Inventory, Payments, Shipping |
| Client | Calls the facade (or, when needed, the subsystem) | Controller, job, CLI |
Client Checkout (facade) Inventory Payments Shipping
1 PlaceOrder(o) ──▶ Reserve(sku, qty) ──▶ ok res-book
2 Authorize(cust, amt) ─────────────────▶ error "above limit"
3 Release(res-book) ──▶ stock restored
4 ◀── error "checkout: payments: amount above limit" (the client never saw step 3)Real scenarios: a PaymentService in front of a provider SDK with 40 classes; a ReportExporter in front of a query builder, a PDF library and a storage disk; a module's public API in a modular monolith (one class per module that other modules may call); http.Get(url) in Go, which is a facade over DefaultClient, NewRequest, Transport and connection pooling; an SDK's "simple client" next to its low-level API.
Go:
// Facade: one small entry point (Checkout.PlaceOrder) in front of a subsystem
// of inventory, payment and shipping. Callers that need more can still use the
// subsystem types directly; the facade does not hide them, it simplifies.
package main
import (
"context"
"errors"
"fmt"
)
// --- subsystem: three independent parts with their own vocabularies ---
type Inventory struct{ stock map[string]int }
func (i *Inventory) Reserve(_ context.Context, sku string, qty int) (string, error) {
if i.stock[sku] < qty {
return "", fmt.Errorf("inventory: %s: only %d left", sku, i.stock[sku])
}
i.stock[sku] -= qty
return "res-" + sku, nil
}
func (i *Inventory) Release(_ context.Context, reservationID string) { _ = reservationID }
type Payments struct{}
func (Payments) Authorize(_ context.Context, customer string, cents int64) (string, error) {
if cents > 100_000 {
return "", errors.New("payments: amount above limit")
}
return "auth-" + customer, nil
}
type Shipping struct{}
func (Shipping) CreateLabel(_ context.Context, address string) (string, error) {
return "label-for-" + address, nil
}
// --- facade: the one call 90% of callers need ---
type Checkout struct {
inv *Inventory
pay Payments
ship Shipping
}
type Order struct {
Customer, Address, SKU string
Qty int
PriceCents int64
}
type Receipt struct{ Reservation, Authorization, Label string }
// PlaceOrder hides the ordering rules and the compensation: reserve, then
// charge, then ship, and release the reservation if charging fails.
func (c *Checkout) PlaceOrder(ctx context.Context, o Order) (Receipt, error) {
res, err := c.inv.Reserve(ctx, o.SKU, o.Qty)
if err != nil {
return Receipt{}, err
}
auth, err := c.pay.Authorize(ctx, o.Customer, o.PriceCents*int64(o.Qty))
if err != nil {
c.inv.Release(ctx, res)
return Receipt{}, fmt.Errorf("checkout: %w", err)
}
label, err := c.ship.CreateLabel(ctx, o.Address)
if err != nil {
return Receipt{}, fmt.Errorf("checkout: %w", err)
}
return Receipt{res, auth, label}, nil
}
func main() {
c := &Checkout{inv: &Inventory{stock: map[string]int{"book": 3}}}
r, err := c.PlaceOrder(context.Background(), Order{"ada", "Tehran", "book", 2, 1500})
fmt.Println(r, err)
// Output: {res-book auth-ada label-for-Tehran} <nil>
}Laravel: the same facade as a plain class, then a Laravel facade (static proxy) that points at it, so you can see that the two words mean different things.
<?php
// 1) A GoF Facade: one class, one simple method, in front of a subsystem.
namespace App\Checkout;
use App\Inventory\InventoryService;
use App\Payments\PaymentGateway;
use App\Shipping\ShippingService;
final class CheckoutFacade
{
public function __construct(
private InventoryService $inventory,
private PaymentGateway $payments,
private ShippingService $shipping,
) {}
public function placeOrder(PlaceOrderData $data): Receipt
{
$reservation = $this->inventory->reserve($data->sku, $data->qty);
try {
$auth = $this->payments->authorize($data->customerId, $data->totalCents());
} catch (\Throwable $e) {
$this->inventory->release($reservation); // compensation lives here, not in controllers
throw $e;
}
return new Receipt(
reservation: $reservation,
authorization: $auth,
label: $this->shipping->createLabel($data->address),
);
}
}
// 2) A Laravel facade is a different thing: a STATIC PROXY to a container binding.
namespace App\Support\Facades;
use Illuminate\Support\Facades\Facade;
/**
* @method static \App\Checkout\Receipt placeOrder(\App\Checkout\PlaceOrderData $data)
*
* @see \App\Checkout\CheckoutFacade
*/
final class Checkout extends Facade
{
protected static function getFacadeAccessor(): string
{
// Facade::__callStatic() resolves this binding and forwards the call.
return \App\Checkout\CheckoutFacade::class;
}
}
// 3) Using both: the controller calls the static proxy, which reaches the GoF facade.
namespace App\Http\Controllers;
use App\Checkout\PlaceOrderData;
use App\Http\Requests\PlaceOrderRequest;
use App\Support\Facades\Checkout;
use Illuminate\Http\JsonResponse;
final class OrderController
{
public function store(PlaceOrderRequest $request): JsonResponse
{
$receipt = Checkout::placeOrder(PlaceOrderData::fromRequest($request));
return response()->json($receipt, 201);
}
}
// 4) Real-time facade: prefix the import with "Facades\" and any class works statically.
// use Facades\App\Checkout\CheckoutFacade;
// CheckoutFacade::placeOrder($data);
// 5) In tests the static proxy is swappable, which a real static method is not:
// Checkout::shouldReceive('placeOrder')->once()->andReturn($fakeReceipt);Consequences: fewer dependencies in clients (a controller imports one class instead of three); the subsystem can change behind a stable surface; one place for ordering and compensation rules. The cost: a facade that grows a method for every use case becomes a god class (see SRP); a facade that only forwards one-to-one adds a layer and no value.
When not to use: when callers really need the subsystem's full flexibility (a facade with 30 pass-through methods is a mirror, not a simplification); when there is only one caller (inline it); when the "subsystem" is one class (that is an Adapter or nothing).
Laravel facades are static proxies, not GoF facades Important
In plain words: Cache::get('k') is not a static method. The Cache class has none. PHP calls Facade::__callStatic('get', ['k']), which asks the container for the cache binding and calls get on that object.
Common misunderstanding: "Facades are global static state, so they cannot be tested." Laravel's docs answer it: facades give "a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods", because the object behind them can be swapped: Cache::shouldReceive('get')->with('key')->andReturn('value').
Definition: a Laravel facade is a class extending Illuminate\Support\Facades\Facade whose getFacadeAccessor() returns a container key. In the framework source, __callStatic does $instance = static::getFacadeRoot(); … return $instance->$method(...$args); and resolved instances are cached in static::$resolvedInstance. In GoF terms it is a Proxy (same operations as the subject, forwards every call) reached through a Service Locator. A real-time facade (use Facades\App\Contracts\Publisher;) generates such a proxy for any class on the fly.
Code Facade (static) Container CacheManager
1 Cache::get('user:42') ──▶ __callStatic('get', [...])
2 getFacadeRoot() ─────────────▶ make('cache') ──▶ (resolved once, cached)
3 $instance->get('user:42') ──────────────────────▶ Redis store ->get()
4 ◀── value
in a test: Cache::shouldReceive('get') swaps step 2's object for a Mockery mock| GoF Facade | Laravel facade | |
|---|---|---|
| What is behind it | Many subsystem classes | One container binding |
| Interface | New, simpler, higher-level | The same methods as the object behind it |
| Static? | No, an ordinary object you inject | Yes, static syntax via __callStatic |
| Closest GoF pattern | Facade | Proxy (+ Service Locator) |
| Main risk | Grows into a god class | "class scope creep" (Laravel docs): many facades in one class hide its dependencies |
Adapter Must-know
In plain words: a small class that makes something with the wrong shape fit the shape your code expects. The plug converter.
Common misunderstanding: "An adapter is any class that calls an external API." An adapter implements an interface the client already uses and translates to the adaptee. A class that calls Stripe and exposes Stripe's own method names to the rest of your app is not an adapter; it is a thin wrapper that still couples you to Stripe.
Definition (GoF intent): "Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces." Also known as Wrapper.
Problem: your domain says SmsSender.Send(ctx, to, text) error. The vendor SDK says SubmitMessage(msisdn string, body []byte, flags int) LegacyResult with numeric codes, no context, and phone numbers without +. You cannot change the SDK, and you must not let LegacyResult leak into checkout.
| Participant | Role | In the snippet |
|---|---|---|
| Target | The interface the client uses | SmsSender |
| Client | Collaborates with objects through Target | Checkout, notification code |
| Adaptee | Existing class with an incompatible interface | LegacySMSClient (vendor SDK) |
| Adapter | Implements Target, holds the Adaptee, translates | LegacySMSAdapter |
Client Adapter Adaptee (vendor)
1 Send(ctx,"+98912…","…") ──▶ ctx.Err()? no
2 msisdn = "98912…" (strip +, 00)
3 SubmitMessage("98912…", []byte, 0) ──▶ {Code: 17, Msg: "INVALID_DEST"}
4 ◀── error "sms: vendor code 17 (INVALID_DEST)" (client never sees LegacyResult)Class adapter vs object adapter Good to know. GoF describes two forms. A class adapter inherits from the adaptee (C++ private inheritance; in PHP class Adapter extends Vendor implements Target); it can override adaptee behaviour but is welded to one concrete class. An object adapter holds a reference to the adaptee; it works with the adaptee's subclasses too, and it is the only form available in Go. A two-way adapter implements both interfaces so old and new code can each see the object as their own. Prefer the object form.
Real scenarios: vendor SDKs (SMS, payment, email, maps) behind your own port; Laravel's cache stores (Redis, Memcached, DynamoDB, database) behind Illuminate\Contracts\Cache\Store; Flysystem ("one interface to interact with many types of filesystems") with Local, FTP, SFTP and S3 adapters behind Laravel's Storage; PSR-18 clients that adapt Guzzle or Symfony HttpClient to sendRequest(RequestInterface): ResponseInterface; http.HandlerFunc, which adapts a function to the Handler interface; io.NopCloser, which adapts a Reader into a ReadCloser; the database/sql drivers.
Go:
// Adapter: make a third-party SDK with the "wrong" shape satisfy the port our
// code owns. Also shows Go's most famous function adapter, http.HandlerFunc.
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
)
// Port: what our application wants (owned by us, named in our language).
type SMSSender interface {
Send(ctx context.Context, to, text string) error
}
// Adaptee: imagine this is github.com/acme/legacysms; we cannot change it.
type LegacySMSClient struct{}
type LegacyResult struct {
Code int // 0 = ok, anything else = vendor error code
Msg string
}
func (LegacySMSClient) SubmitMessage(msisdn string, body []byte, flags int) LegacyResult {
if !strings.HasPrefix(msisdn, "98") {
return LegacyResult{Code: 17, Msg: "INVALID_DEST"}
}
return LegacyResult{Code: 0, Msg: "OK"}
}
// Adapter: implements the port, wraps the adaptee, translates both ways.
type LegacySMSAdapter struct{ client LegacySMSClient }
func (a LegacySMSAdapter) Send(ctx context.Context, to, text string) error {
if err := ctx.Err(); err != nil { // the SDK has no context; we honour ours
return err
}
msisdn := strings.TrimPrefix(strings.TrimPrefix(to, "+"), "00")
res := a.client.SubmitMessage(msisdn, []byte(text), 0)
if res.Code != 0 {
return fmt.Errorf("sms: vendor code %d (%s)", res.Code, res.Msg)
}
return nil
}
// Compile-time check that the adapter satisfies the port.
var _ SMSSender = LegacySMSAdapter{}
func main() {
var s SMSSender = LegacySMSAdapter{}
fmt.Println(s.Send(context.Background(), "+989121234567", "your code is 4821"))
fmt.Println(s.Send(context.Background(), "+15551234567", "hi"))
// Function adapter from net/http: a plain func becomes a Handler.
hello := func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "hello") }
var h http.Handler = http.HandlerFunc(hello)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("GET", "/", nil))
fmt.Println(rec.Body.String())
// Output:
// <nil>
// sms: vendor code 17 (INVALID_DEST)
// hello
}Laravel: an SDK adapter bound to your port, plus the two adapter points Laravel documents: Cache::extend (a custom Store) and Storage::extend (a Flysystem adapter wrapped in Laravel's FilesystemAdapter).
<?php
// 1) Object adapter for a third-party SDK: our port, their client.
namespace App\Notifications\Sms;
interface SmsSender
{
public function send(string $to, string $text): void;
}
final class SmsDeliveryFailed extends \RuntimeException {}
/** Adaptee: a vendor SDK we cannot change (method names, codes and types are theirs). */
final class LegacySmsClient
{
/** @return array{code: int, msg: string} */
public function submitMessage(string $msisdn, string $body, int $flags = 0): array
{
return str_starts_with($msisdn, '98')
? ['code' => 0, 'msg' => 'OK']
: ['code' => 17, 'msg' => 'INVALID_DEST'];
}
}
final class LegacySmsAdapter implements SmsSender
{
public function __construct(private LegacySmsClient $client) {}
public function send(string $to, string $text): void
{
$msisdn = ltrim(preg_replace('/^00/', '', $to), '+');
$result = $this->client->submitMessage($msisdn, $text);
if ($result['code'] !== 0) {
throw new SmsDeliveryFailed("vendor code {$result['code']} ({$result['msg']})");
}
}
}
// 2) Laravel's own adapters: a cache store and a filesystem disk are adapters
// behind one interface (Illuminate\Contracts\Cache\Store, Flysystem's FilesystemAdapter).
namespace App\Providers;
use App\Extensions\MongoStore;
use App\Notifications\Sms\LegacySmsAdapter;
use App\Notifications\Sms\LegacySmsClient;
use App\Notifications\Sms\SmsSender;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Filesystem\FilesystemAdapter;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\ServiceProvider;
use League\Flysystem\Filesystem;
use Spatie\Dropbox\Client as DropboxClient;
use Spatie\FlysystemDropbox\DropboxAdapter;
final class AdapterServiceProvider extends ServiceProvider
{
public function register(): void
{
// The rest of the app type-hints SmsSender and never sees the vendor.
$this->app->singleton(SmsSender::class, fn () => new LegacySmsAdapter(new LegacySmsClient));
// Custom cache driver: MongoStore implements Illuminate\Contracts\Cache\Store.
$this->app->booting(function () {
Cache::extend('mongo', fn (Application $app) => Cache::repository(new MongoStore));
});
}
public function boot(): void
{
// Custom disk: a community Flysystem adapter wrapped in Laravel's FilesystemAdapter.
Storage::extend('dropbox', function (Application $app, array $config) {
$adapter = new DropboxAdapter(new DropboxClient($config['authorization_token']));
return new FilesystemAdapter(new Filesystem($adapter, $config), $adapter, $config);
});
}
}
// Callers stay identical whichever adapter is configured:
// Cache::store('mongo')->put('k', 'v', 60);
// Storage::disk('dropbox')->put('invoices/42.pdf', $pdf);Consequences: the vendor is replaceable (write another adapter); vendor types stop at the adapter; tests use a fake implementation of the port. The cost: one more type; translation can lose information (a vendor's rich error becomes your three error kinds) and that loss must be a decision, not an accident.
When not to use: when the "adaptee" is your own code (change it instead); when the interfaces already match (Go's implicit interfaces often make an adapter unnecessary: if the SDK type already has Send(ctx, to, text) error, it already satisfies your port); when the translation is a whole model mapping across a boundary: then you need an anti-corruption layer, which is Adapter plus Facade plus a translator.
Composite Must-know
In plain words: a container and its items answer the same questions, so the caller never checks "is this one thing or a group?". The hotel answering "how many guests?" for a room, a floor or the building.
Common misunderstanding: "Composite means any tree." A tree of different node types that the client must switch on is just a tree. Composite is the uniform interface: the client calls Size() on any node, and the container implements Size() by delegating to its children.
Definition (GoF intent): "Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly."
Problem: a disk-usage tool, a menu with groups and items, a pricing bundle that contains products and other bundles, a permission set that contains permissions and roles, an expression (2 + 3 + 5) * 4. Every one of them is code full of if node is folder then loop else return until you give leaves and containers one interface.
| Participant | Role | In the snippet |
|---|---|---|
| Component | Interface for all objects in the tree | Node, Expr, MenuComponent, ValidationRule |
| Leaf | Has no children; does the work | File, Num, MenuItem, Iban |
| Composite | Stores children; implements operations by delegating | Dir, Sum, MenuGroup, AllOf |
| Client | Calls Component operations | root.Size(), $menu->render($user) |
Client Dir app/ File main.go Dir internal/ File db.go File http.go
1 Size() ──────▶ for children:
2 ├─ Size() ───────▶ 1200
3 └─ Size() ─────────────────────────▶ for children:
4 ├─ Size() ──────▶ 800
5 └─ Size() ─────────────────────▶ 950
6 ◀── 1750
7 ◀── 2950Transparency vs safety Good to know. Where do Add/Remove live? GoF: "Defining the child management interface at the root of the class hierarchy gives you transparency… It costs you safety, however, because clients may try to do meaningless things like add and remove objects from leaves." Declaring them only on the Composite gives safety and loses transparency. GoF chose transparency for the book; Go code almost always chooses safety (Add is a method on *Dir, not on Node), because Go interfaces are small by habit (ISP).
Real scenarios: file systems and object storage "folders"; UI component trees (Blade components containing components, React trees); ASTs and query builders (WHERE (a AND (b OR c))); org charts and cost centres; product bundles; permission groups; io.MultiWriter and io.MultiReader in Go (one writer made of many writers, a flat composite); Laravel's array of rules per field, and a rule object that combines rules.
Go:
// Composite: leaves and containers share one interface, so client code
// (Size, Eval) never asks "is this a file or a folder?".
package main
import (
"fmt"
"strings"
)
// --- file tree ---
type Node interface {
Name() string
Size() int64
print(b *strings.Builder, depth int)
}
type File struct {
name string
bytes int64
}
func (f File) Name() string { return f.name }
func (f File) Size() int64 { return f.bytes }
func (f File) print(b *strings.Builder, d int) {
fmt.Fprintf(b, "%s%s (%d)\n", strings.Repeat(" ", d), f.name, f.bytes)
}
type Dir struct {
name string
children []Node
}
func (d *Dir) Add(n ...Node) *Dir { d.children = append(d.children, n...); return d }
func (d *Dir) Name() string { return d.name + "/" }
// Size is the composite operation: it delegates to children and sums.
func (d *Dir) Size() int64 {
var total int64
for _, c := range d.children {
total += c.Size()
}
return total
}
func (d *Dir) print(b *strings.Builder, depth int) {
fmt.Fprintf(b, "%s%s (%d)\n", strings.Repeat(" ", depth), d.Name(), d.Size())
for _, c := range d.children {
c.print(b, depth+1)
}
}
// --- expression tree: the same shape, a different domain ---
type Expr interface{ Eval() float64 }
type Num float64
func (n Num) Eval() float64 { return float64(n) }
type Sum []Expr // a composite: any number of children
func (s Sum) Eval() float64 {
var t float64
for _, e := range s {
t += e.Eval()
}
return t
}
type Mul struct{ L, R Expr }
func (m Mul) Eval() float64 { return m.L.Eval() * m.R.Eval() }
func main() {
root := (&Dir{name: "app"}).Add(
File{"main.go", 1200},
(&Dir{name: "internal"}).Add(File{"db.go", 800}, File{"http.go", 950}),
)
var b strings.Builder
root.print(&b, 0)
fmt.Print(b.String())
// (2 + 3 + 5) * 4
fmt.Println(Mul{Sum{Num(2), Num(3), Num(5)}, Num(4)}.Eval())
// Output:
// app/ (2950)
// main.go (1200)
// internal/ (1750)
// db.go (800)
// http.go (950)
// 40
}Laravel: a menu tree whose groups disappear when the user can see none of their items, and a composite validation rule.
<?php
// 1) Composite menu: items and groups share one interface.
namespace App\Navigation;
use App\Models\User;
interface MenuComponent
{
/** @return list<array{label: string, url?: string, children?: list<array<string, mixed>>}> */
public function render(User $user): array;
}
final class MenuItem implements MenuComponent
{
public function __construct(
private string $label,
private string $route,
private ?string $ability = null,
) {}
public function render(User $user): array
{
if ($this->ability !== null && $user->cannot($this->ability)) {
return [];
}
return [['label' => $this->label, 'url' => route($this->route)]];
}
}
final class MenuGroup implements MenuComponent
{
/** @var list<MenuComponent> */
private array $children = [];
public function __construct(private string $label) {}
public function add(MenuComponent ...$children): self
{
array_push($this->children, ...$children);
return $this;
}
public function render(User $user): array
{
$rendered = array_merge(...array_map(fn (MenuComponent $c) => $c->render($user), $this->children));
// An empty group disappears: the composite decides, the caller never checks.
return $rendered === [] ? [] : [['label' => $this->label, 'children' => $rendered]];
}
}
// Usage (e.g. in a view composer):
// $menu = (new MenuGroup('Admin'))->add(
// new MenuItem('Orders', 'orders.index', 'viewAny-order'),
// (new MenuGroup('Reports'))->add(new MenuItem('Revenue', 'reports.revenue', 'view-revenue')),
// );
// $tree = $menu->render($request->user());
// 2) Composite validation rule: one rule object made of other rule objects.
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
final class AllOf implements ValidationRule
{
/** @var list<ValidationRule> */
private array $rules;
public function __construct(ValidationRule ...$rules)
{
$this->rules = $rules;
}
public function validate(string $attribute, mixed $value, Closure $fail): void
{
foreach ($this->rules as $rule) {
$failed = false;
$rule->validate($attribute, $value, function (string $message) use ($fail, &$failed) {
$failed = true;
return $fail($message); // keep the PotentiallyTranslatedString for chaining
});
if ($failed) {
return; // stop at the first failing child, like "bail"
}
}
}
}
final class Iban implements ValidationRule
{
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (! is_string($value) || ! preg_match('/^[A-Z]{2}\d{2}[A-Z0-9]{10,30}$/', $value)) {
$fail('The :attribute must be a valid IBAN.');
}
}
}
final class NotSanctioned implements ValidationRule
{
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (str_starts_with((string) $value, 'XX')) {
$fail('The :attribute belongs to a blocked country.');
}
}
}
// In a Form Request: 'iban' => ['required', new AllOf(new Iban, new NotSanctioned)],Consequences: clients get simple; new leaf and composite types slot in without client changes (Open–Closed). The cost: the design can become "overly general" (GoF): it is hard to restrict a composite to certain child types, so you need run-time checks; deep trees mean deep recursion; computing aggregates on every call (Size() walks the whole tree) may need caching with invalidation.
When not to use: when leaves and groups really need different interfaces (forcing one interface means many no-op methods, a Liskov smell); when the structure is a flat list; when the tree lives in a database and the operation is an aggregate: a recursive SQL query is usually faster than loading the tree into objects.
-- The same "Size of a folder" as one recursive query (WITH RECURSIVE, standard SQL).
WITH RECURSIVE tree AS (
SELECT id, parent_id, size_bytes FROM nodes WHERE id = 1 -- the root "app/"
UNION ALL
SELECT n.id, n.parent_id, n.size_bytes FROM nodes n JOIN tree t ON n.parent_id = t.id
)
SELECT sum(size_bytes) AS total FROM tree; -- 2950Proxy Must-know
In plain words: a stand-in with exactly the same interface as the real object, which decides whether, when and how to call it. The room key card.
Common misunderstanding: "A proxy is a network thing." GoF's proxies are mostly in-process: a virtual proxy that delays creating an expensive object, a protection proxy that checks permissions, a smart reference that counts or caches. The network reverse proxy is one kind (the remote proxy) seen from the outside.
Definition (GoF intent): "Provide a surrogate or placeholder for another object to control access to it." GoF lists four kinds: a remote proxy ("a local representative for an object in a different address space"), a virtual proxy ("creates expensive objects on demand"), a protection proxy ("controls access to the original object") and a smart reference (extra actions when the object is accessed: counting references, loading on first use, locking). Later literature adds the caching proxy as a common smart-reference case.
Problem: product lookups hit SQL 400 times per page; a PDF renderer loads 40 MB of fonts at boot even on requests that never render a PDF; unreleased products must be invisible to customers; the catalog lives in another service. In each case callers should keep calling Product(id).
| Participant | Role | In the snippet |
|---|---|---|
| Subject | Interface shared by proxy and real subject | Catalog |
| RealSubject | The object that does the real work | dbCatalog, EloquentCatalog |
| Proxy | Holds a reference to the RealSubject, controls access | CachingCatalog, LazyCatalog, ProtectedCatalog, ReverseProxy |
Client CachingCatalog (proxy) dbCatalog (real)
1 Product(7) ────▶ cache miss
2 next.Product(7) ─────────────────────────▶ SELECT … WHERE id = 7 (5 ms)
3 store {p7, exp = now + 1m}
4 Product(7) ────▶ cache hit, not expired ◀── returns in microseconds; no SQL
5 Product(7) ────▶ cache hit queries after 3 reads: 1Real scenarios: caching repositories (with the invalidation problems on Caching); lazy service construction (sync.OnceValues, PHP 8.4 newLazyProxy, Symfony's lazy services); authorization wrappers; gRPC client stubs and SOAP stubs (remote proxies); httputil.ReverseProxy, NGINX, HAProxy and Envoy at the network edge; copy-on-write (GoF describes it as a smart-reference optimisation); ORMs' lazy loading (see below).
Go: caching, virtual and protection proxies in one file, then a remote proxy using the standard library's reverse proxy.
// Proxy: same interface as the real subject, but controls access to it.
// Three kinds from GoF in one file: caching (a smart reference), virtual
// (lazy creation) and protection (authorization).
package main
import (
"context"
"errors"
"fmt"
"sync"
"time"
)
type Product struct {
ID int
Name string
Cents int64
}
// Subject: the interface clients depend on.
type Catalog interface {
Product(ctx context.Context, id int) (Product, error)
}
// RealSubject: slow, e.g. SQL or a remote service.
type dbCatalog struct{ queries int }
func (d *dbCatalog) Product(_ context.Context, id int) (Product, error) {
d.queries++
time.Sleep(5 * time.Millisecond) // pretend network + SQL
return Product{ID: id, Name: fmt.Sprintf("p%d", id), Cents: 990}, nil
}
// --- caching proxy (cache-aside with TTL) ---
type entry struct {
p Product
exp time.Time
}
type CachingCatalog struct {
next Catalog
ttl time.Duration
mu sync.Mutex
m map[int]entry
}
func NewCachingCatalog(next Catalog, ttl time.Duration) *CachingCatalog {
return &CachingCatalog{next: next, ttl: ttl, m: map[int]entry{}}
}
func (c *CachingCatalog) Product(ctx context.Context, id int) (Product, error) {
c.mu.Lock()
e, ok := c.m[id]
c.mu.Unlock()
if ok && time.Now().Before(e.exp) {
return e.p, nil
}
p, err := c.next.Product(ctx, id)
if err != nil {
return Product{}, err // never cache failures here
}
c.mu.Lock()
c.m[id] = entry{p, time.Now().Add(c.ttl)}
c.mu.Unlock()
return p, nil
}
// --- virtual proxy: the expensive subject is built on first use ---
type LazyCatalog struct {
get func() (Catalog, error)
}
func NewLazyCatalog(build func() (Catalog, error)) *LazyCatalog {
return &LazyCatalog{get: sync.OnceValues(build)} // Go 1.21+
}
func (l *LazyCatalog) Product(ctx context.Context, id int) (Product, error) {
c, err := l.get()
if err != nil {
return Product{}, err
}
return c.Product(ctx, id)
}
// --- protection proxy: checks the caller before forwarding ---
type ctxKey struct{}
func WithRole(ctx context.Context, role string) context.Context {
return context.WithValue(ctx, ctxKey{}, role)
}
var ErrForbidden = errors.New("forbidden")
type ProtectedCatalog struct{ next Catalog }
func (p ProtectedCatalog) Product(ctx context.Context, id int) (Product, error) {
if role, _ := ctx.Value(ctxKey{}).(string); role != "staff" && id >= 1000 {
return Product{}, ErrForbidden // ids >= 1000 are unreleased products
}
return p.next.Product(ctx, id)
}
func main() {
db := &dbCatalog{}
var c Catalog = NewCachingCatalog(db, time.Minute)
for range 3 {
_, _ = c.Product(context.Background(), 7)
}
fmt.Println("queries after 3 reads:", db.queries)
built := 0
lazy := NewLazyCatalog(func() (Catalog, error) { built++; return &dbCatalog{}, nil })
fmt.Println("built before first call:", built)
_, _ = lazy.Product(context.Background(), 1)
_, _ = lazy.Product(context.Background(), 2)
fmt.Println("built after two calls:", built)
guarded := ProtectedCatalog{next: c}
_, err := guarded.Product(WithRole(context.Background(), "customer"), 1001)
fmt.Println(err)
// Output:
// queries after 3 reads: 1
// built before first call: 0
// built after two calls: 1
// forbidden
}// A remote proxy at the network level: httputil.ReverseProxy forwards the
// request to a backend and copies the response back. The client cannot tell.
package main
import (
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
"net/http/httputil"
"net/url"
)
func main() {
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "backend saw path=%s xff=%q", r.URL.Path, r.Header.Get("X-Forwarded-For"))
}))
defer backend.Close()
target, err := url.Parse(backend.URL)
if err != nil {
log.Fatal(err)
}
proxy := &httputil.ReverseProxy{
// Rewrite replaces the deprecated Director hook (see the httputil docs).
Rewrite: func(pr *httputil.ProxyRequest) {
pr.SetURL(target) // scheme, host and base path of the backend
pr.SetXForwarded()
pr.Out.Header.Set("X-Proxy", "academy")
},
ModifyResponse: func(resp *http.Response) error {
resp.Header.Set("X-Served-By", "edge-1")
return nil
},
}
front := httptest.NewServer(proxy)
defer front.Close()
resp, err := http.Get(front.URL + "/orders/42")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body), "|", resp.Header.Get("X-Served-By"))
// Output: backend saw path=/orders/42 xff="127.0.0.1" | edge-1
}Laravel: a caching proxy and a protection proxy that share the Catalog interface with the Eloquent implementation, and a virtual proxy built with PHP 8.4 lazy objects.
<?php
namespace App\Catalog;
use App\Models\Product;
use Illuminate\Contracts\Cache\Repository as Cache;
use Illuminate\Contracts\Auth\Access\Gate;
use Illuminate\Auth\Access\AuthorizationException;
// Subject: what callers type-hint.
interface Catalog
{
public function find(int $id): ?Product;
}
// RealSubject: Eloquent + SQL.
final class EloquentCatalog implements Catalog
{
public function find(int $id): ?Product
{
return Product::query()->find($id);
}
}
// 1) Caching proxy (cache-aside). Same interface, fewer queries.
final class CachingCatalog implements Catalog
{
public function __construct(
private Catalog $next,
private Cache $cache,
private int $ttlSeconds = 300,
) {}
public function find(int $id): ?Product
{
// remember() is on the Cache contract; Cache::flexible() adds stale-while-revalidate.
return $this->cache->remember(
"catalog:product:{$id}",
$this->ttlSeconds,
fn () => $this->next->find($id),
);
}
}
// 2) Protection proxy: authorization before forwarding.
final class AuthorizedCatalog implements Catalog
{
public function __construct(private Catalog $next, private Gate $gate) {}
public function find(int $id): ?Product
{
$product = $this->next->find($id);
if ($product !== null && $product->unreleased && $this->gate->denies('view-unreleased')) {
throw new AuthorizationException('Product not released yet.');
}
return $product;
}
}
// 3) Virtual proxy with PHP 8.4 lazy objects: the heavy object is built on first property access.
final class PdfRenderer
{
public function __construct(public readonly string $fontCache)
{
// imagine: loads 40 MB of fonts
}
public function render(string $html): string
{
return "%PDF-1.7 ({$this->fontCache}) ".strlen($html);
}
}
final class LazyFactory
{
public static function pdfRenderer(): PdfRenderer
{
$reflector = new \ReflectionClass(PdfRenderer::class);
return $reflector->newLazyProxy(fn (PdfRenderer $proxy) => new PdfRenderer(storage_path('fonts')));
}
}
// Wiring in a service provider: callers ask for Catalog and get proxy(proxy(real)).
// $this->app->singleton(Catalog::class, fn ($app) => new AuthorizedCatalog(
// new CachingCatalog(new EloquentCatalog, $app->make(Cache::class)),
// $app->make(Gate::class),
// ));
//
// Eloquent's lazy loading is the Lazy Load pattern, a cousin of the virtual proxy:
// $order->customer // first access runs: select * from customers where id = ?
// Turn it into an error outside production (AppServiceProvider::boot):
// Model::preventLazyLoading(! $this->app->isProduction());Eloquent lazy loading is a proxy-like Lazy Load, and the classic way it goes wrong Important. Laravel's docs: "Dynamic relationship properties perform "lazy loading", meaning they will only load their relationship data when you actually access them." There is no separate proxy object (the model's magic __get runs the query on first access), so it is Fowler's Lazy Load pattern rather than a GoF virtual proxy, but the trade-off is the same: the caller cannot see the cost. In a loop it becomes the N+1 problem:
-- foreach ($orders as $order) echo $order->customer->name; (50 orders, lazy)
select * from orders limit 50;
select * from customers where customers.id = 17 limit 1;
select * from customers where customers.id = 4 limit 1;
-- … 48 more: 51 queries
-- Order::with('customer')->limit(50)->get(); (eager)
select * from orders limit 50;
select * from customers where customers.id in (4, 17, 23, …); -- 2 queriesModel::preventLazyLoading(! $this->app->isProduction()) turns the hidden query into an exception during development. The full story is on ORM Pitfalls.
Consequences: callers stay unchanged while you add caching, laziness, security or distance. The cost: hidden latency (a call that looks local may be a network hop; that is the first of the fallacies of distributed computing); stale data in caching proxies; identity confusion (proxy !== realSubject); with lazy proxies, errors move from boot time to first use.
When not to use: when the caller should know about the cost (make remote calls look remote: a ctx, a timeout, an error); when the cache has no invalidation story; when a protection check belongs in a policy at the edge instead of in every object.
Decorator Must-know
In plain words: a layer with the same interface as what it wraps, which does one extra thing before or after passing the call on. Layers stack. The phone in a battery case in a waterproof pouch.
Common misunderstanding: "Python's @decorator and PHP attributes are the Decorator pattern." A Python function decorator is a higher-order function that wraps a function; it is in the same spirit (and Go middleware is exactly that shape), but GoF's Decorator is about objects that share an interface so they can be composed at run time. PHP attributes (#[...]) are metadata, not wrappers at all.
Definition (GoF intent): "Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality." Also known as Wrapper.
Problem: an HTTP client needs logging, metrics, retries, auth headers and a circuit breaker, in different combinations per call site. Subclassing gives LoggingRetryingClient, MeteredRetryingAuthClient… one class per combination. Decorators give one class per concern.
| Participant | Role | In the snippet |
|---|---|---|
| Component | The interface | io.Writer, http.Handler, Doer, PaymentGateway |
| ConcreteComponent | The real object | bytes.Buffer, your handler, *http.Client, the real gateway |
| Decorator | Holds a Component, implements Component, forwards | countingWriter, Logging(...), LoggingPaymentGateway |
| ConcreteDecorator | Adds one responsibility | gzip.Writer, bufio.Writer, RequireHeader, AddSecurityHeaders |
Order of wrapping = order of execution (outermost runs first, finishes last)
h := Logging(RequireHeader(MaxBytes(app)))
1 request ──▶ Logging: start timer
2 ──▶ RequireHeader: header missing → 401, return (app never runs)
3 ◀── Logging: log status=401
swap the two: h := RequireHeader(Logging(MaxBytes(app)))
4 request ──▶ RequireHeader: 401, return → nothing is logged for rejected requestsReal scenarios: Go I/O (bufio, gzip, io.TeeReader, io.LimitReader, cipher.StreamWriter); HTTP server middleware in Go and Laravel; HTTP client middleware (Guzzle, a Go RoundTripper or Doer wrapper); retry, timeout, circuit breaker and rate-limit wrappers; logging and metrics around repositories and gateways; Laravel's Container::extend to wrap a binding someone else registered; response decorators that add headers or compress.
Go: first the io.Writer chain (bufio → gzip → our counting writer → buffer, with io.TeeReader hashing the input), then the same idea as http.Handler middleware with a ResponseWriter decorator that exposes Unwrap.
// Decorator: every wrapper has the SAME interface as what it wraps, adds one
// responsibility, and can be stacked in any order. Go's io and net/http are
// built from this idea.
package main
import (
"bufio"
"bytes"
"compress/gzip"
"crypto/sha256"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"os"
"strings"
"time"
)
// --- part 1: io.Writer decorators from the standard library ---
// countingWriter is our own decorator: it counts bytes, then forwards.
type countingWriter struct {
w io.Writer
n int64
}
func (c *countingWriter) Write(p []byte) (int, error) {
n, err := c.w.Write(p)
c.n += int64(n)
return n, err
}
func compressAndHash(src io.Reader) (compressed int64, sum [32]byte, err error) {
var out bytes.Buffer
counter := &countingWriter{w: &out} // innermost: counts compressed bytes
zw := gzip.NewWriter(counter) // compresses into the counter
bw := bufio.NewWriterSize(zw, 32<<10) // batches small writes before gzip
h := sha256.New()
tee := io.TeeReader(src, h) // hashes the plain text as it is read
if _, err = io.Copy(bw, tee); err != nil {
return 0, sum, err
}
// Close order matters: flush the outer wrapper first, then the inner one.
if err = bw.Flush(); err != nil {
return 0, sum, err
}
if err = zw.Close(); err != nil {
return 0, sum, err
}
copy(sum[:], h.Sum(nil))
return counter.n, sum, nil
}
// --- part 2: http.Handler middleware is the same pattern ---
type Middleware func(http.Handler) http.Handler
// Chain applies the first middleware outermost: Chain(h, a, b) == a(b(h)).
func Chain(h http.Handler, mws ...Middleware) http.Handler {
for i := len(mws) - 1; i >= 0; i-- {
h = mws[i](h)
}
return h
}
// statusRecorder decorates http.ResponseWriter to capture the status code.
// Unwrap lets http.ResponseController reach Flush/Hijack on the original.
type statusRecorder struct {
http.ResponseWriter
status int
}
func (r *statusRecorder) WriteHeader(code int) {
r.status = code
r.ResponseWriter.WriteHeader(code)
}
func (r *statusRecorder) Unwrap() http.ResponseWriter { return r.ResponseWriter }
func Logging(log *slog.Logger) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(rec, r)
log.Info("http", "method", r.Method, "path", r.URL.Path,
"status", rec.status, "dur_ms", time.Since(start).Milliseconds())
})
}
}
func RequireHeader(name string) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get(name) == "" {
http.Error(w, "missing "+name, http.StatusUnauthorized)
return // short-circuit: the inner handler never runs
}
next.ServeHTTP(w, r)
})
}
}
func main() {
n, sum, err := compressAndHash(strings.NewReader(strings.Repeat("structural patterns ", 500)))
fmt.Printf("gzip bytes=%d sha256=%x err=%v\n", n, sum[:4], err)
log := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey || a.Key == "dur_ms" {
return slog.Attr{} // stable output for the docs
}
return a
},
}))
app := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "ok") })
h := Chain(app, Logging(log), RequireHeader("X-Api-Key"),
func(h http.Handler) http.Handler { return http.MaxBytesHandler(h, 1<<20) }, // stdlib decorator
)
for _, key := range []string{"", "k1"} {
req := httptest.NewRequest("GET", "/orders", nil)
if key != "" {
req.Header.Set("X-Api-Key", key)
}
h.ServeHTTP(httptest.NewRecorder(), req)
}
// Output (gzip size depends on the Go version's compressor):
// gzip bytes=80 sha256=73b7d043 err=<nil>
// level=INFO msg=http method=GET path=/orders status=401
// level=INFO msg=http method=GET path=/orders status=200
}Laravel: logging and metrics decorators stacked with Container::extend, and a middleware that decorates the response.
<?php
namespace App\Payments;
use Psr\Log\LoggerInterface;
interface PaymentGateway
{
public function charge(string $orderId, int $amountMinor, string $currency): ChargeResult;
}
// 1) Logging decorator: same interface, adds one responsibility, forwards.
final class LoggingPaymentGateway implements PaymentGateway
{
public function __construct(private PaymentGateway $inner, private LoggerInterface $log) {}
public function charge(string $orderId, int $amountMinor, string $currency): ChargeResult
{
$start = hrtime(true);
try {
$result = $this->inner->charge($orderId, $amountMinor, $currency);
$this->log->info('payment.charge', ['order' => $orderId, 'ok' => $result->approved,
'ms' => intdiv(hrtime(true) - $start, 1_000_000)]);
return $result;
} catch (\Throwable $e) {
$this->log->warning('payment.charge.failed', ['order' => $orderId, 'error' => $e->getMessage()]);
throw $e;
}
}
}
// 2) Metrics decorator: stacks on top of the logging one without either knowing.
final class CountingPaymentGateway implements PaymentGateway
{
public static int $calls = 0;
public function __construct(private PaymentGateway $inner) {}
public function charge(string $orderId, int $amountMinor, string $currency): ChargeResult
{
self::$calls++;
return $this->inner->charge($orderId, $amountMinor, $currency);
}
}
// 3) Container::extend(): decorate a binding without touching who registered it.
namespace App\Providers;
use App\Payments\CountingPaymentGateway;
use App\Payments\LoggingPaymentGateway;
use App\Payments\PaymentGateway;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\ServiceProvider;
use Psr\Log\LoggerInterface;
final class PaymentDecoratorsProvider extends ServiceProvider
{
public function register(): void
{
// Each extend() wraps the previous result: Counting(Logging(real)).
$this->app->extend(PaymentGateway::class, fn (PaymentGateway $gw, Application $app) =>
new LoggingPaymentGateway($gw, $app->make(LoggerInterface::class)));
$this->app->extend(PaymentGateway::class, fn (PaymentGateway $gw) =>
new CountingPaymentGateway($gw));
}
}
// 4) HTTP middleware is the decorator of the request pipeline;
// this one decorates the RESPONSE after the inner layers ran.
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
final class AddSecurityHeaders
{
public function handle(Request $request, Closure $next): Response
{
$response = $next($request); // inner layers + controller
$response->headers->set('X-Content-Type-Options', 'nosniff');
$response->headers->set('Referrer-Policy', 'strict-origin-when-cross-origin');
return $response;
}
}
// bootstrap/app.php:
// ->withMiddleware(function (Middleware $middleware) {
// $middleware->append(AddSecurityHeaders::class);
// })Middleware: Decorator or Chain of Responsibility? Good to know Both. Structurally each middleware wraps the next handler and has the same interface (Decorator). Behaviourally a middleware may stop the request without calling the next one (PSR-15: "A middleware component MAY create and return a response without delegating to a request handler"), which is the defining move of Chain of Responsibility, covered on Behavioral Patterns. Laravel's docs describe middleware as "a series of "layers" HTTP requests must pass through"; the Go page Middlewares covers the catalogue.
Consequences: responsibilities combine freely, at run time, without subclass explosion (Open–Closed); each decorator is small and testable alone. The cost: "lots of little objects that all look alike" (GoF), which are hard to debug when the chain is long; order matters and is easy to get wrong; "a decorated component is not identical to the component itself", so code that compares identity or type-asserts on the concrete type breaks; a decorator hides optional interfaces of what it wraps (see Mechanics).
When not to use: when the extra behaviour is a core rule (put it in the class); when the order of layers is fixed and never changes (one class may be clearer); when you need to change the component's interface (that is an Adapter).
Bridge Important
In plain words: when something varies along two dimensions, split it into two hierarchies and connect them with a reference, instead of writing one class per combination. The remote control and the TV.
Common misunderstanding: "Bridge is Adapter with a different name." GoF's discussion: "Adapter focuses on resolving incompatibilities between two existing interfaces… Bridge, on the other hand, bridges an abstraction and its (potentially numerous) implementations." Adapter is a repair; Bridge is a plan.
Definition (GoF intent): "Decouple an abstraction from its implementation so that the two can vary independently." Here abstraction means the high-level control layer the client uses (a notification, a remote, a repository API), and implementation (GoF's Implementor) means the platform-specific layer it delegates to (a transport, a TV, a database driver). It does not mean "interface vs class".
Problem: notifications of kind OrderShipped, SecurityAlert, InvoiceDue, each sent by email, SMS, Slack or push. With subclassing: OrderShippedEmail, OrderShippedSms… 3 × 4 = 12 classes, and a fifth channel adds three more. With Bridge: 3 + 4 = 7 types, and a fifth channel adds one.
| Participant | Role | In the snippet |
|---|---|---|
| Abstraction | Client-facing API; holds an Implementor | Notification (with transport) |
| RefinedAbstraction | Variants of the abstraction | OrderShipped, SecurityAlert |
| Implementor | Interface for the implementation side | Transport.Deliver(to, subject, body) |
| ConcreteImplementor | Platform-specific implementations | EmailTransport, SMSTransport, SlackTransport |
Code OrderShipped (abstraction) SMSTransport (implementor)
1 OrderShipped{sms,…}.Send(ctx, to) ──▶ build subject + body (WHAT)
2 transport.Deliver(to, s, b) ──▶ truncate to 30 chars, send (HOW)
3 new channel "push": write PushTransport; zero edits to OrderShipped or SecurityAlert
4 new kind "InvoiceDue": write one type; it works on all four transports at onceReal scenarios: Go's database/sql (the abstraction you call: DB, Tx, Rows) over database/sql/driver (the implementor each driver provides: pgx, mysql, sqlite); log/slog's Logger (front end) over slog.Handler (text, JSON, OpenTelemetry back ends); Laravel's Storage API over Flysystem adapters; Laravel's notifications over channels; a UI widget toolkit over platform windowing systems (GoF's own example); a report (abstraction) over renderers (PDF, CSV, HTML).
Go:
// Bridge: two hierarchies that vary independently. The abstraction side
// (what kind of notification) holds a reference to the implementor side
// (how bytes travel). 2 kinds + 3 transports = 5 types, not 2 x 3 = 6.
package main
import (
"context"
"fmt"
"strings"
)
// Implementor: a transport knows how to deliver a rendered message.
type Transport interface {
Deliver(ctx context.Context, to string, subject, body string) error
}
type EmailTransport struct{}
func (EmailTransport) Deliver(_ context.Context, to, subject, body string) error {
fmt.Printf("[email to %s] %s: %s\n", to, subject, body)
return nil
}
type SMSTransport struct{ maxLen int }
func (s SMSTransport) Deliver(_ context.Context, to, _ string, body string) error {
if len(body) > s.maxLen {
body = body[:s.maxLen-3] + "..."
}
fmt.Printf("[sms to %s] %s\n", to, body)
return nil
}
type SlackTransport struct{ channel string }
func (s SlackTransport) Deliver(_ context.Context, _ string, subject, body string) error {
fmt.Printf("[slack %s] *%s* %s\n", s.channel, subject, body)
return nil
}
// Abstraction: a notification decides WHAT to say and WHEN, never HOW.
type Notification struct {
transport Transport // the bridge
}
// Refined abstractions.
type OrderShipped struct {
Notification
OrderID, Tracking string
}
func (n OrderShipped) Send(ctx context.Context, to string) error {
return n.transport.Deliver(ctx, to, "Order shipped",
fmt.Sprintf("Order %s is on its way, tracking %s", n.OrderID, n.Tracking))
}
type SecurityAlert struct {
Notification
Event string
}
// SecurityAlert adds behaviour of its own (urgency) without knowing transports.
func (n SecurityAlert) Send(ctx context.Context, to string) error {
return n.transport.Deliver(ctx, to, "SECURITY", strings.ToUpper(n.Event))
}
func main() {
ctx := context.Background()
sms := SMSTransport{maxLen: 30}
_ = OrderShipped{Notification{EmailTransport{}}, "A-17", "TRK9"}.Send(ctx, "ada@example.com")
_ = OrderShipped{Notification{sms}, "A-17", "TRK9"}.Send(ctx, "+98912")
_ = SecurityAlert{Notification{SlackTransport{"#sec"}}, "new login from unknown device"}.Send(ctx, "")
// Output:
// [email to ada@example.com] Order shipped: Order A-17 is on its way, tracking TRK9
// [sms to +98912] Order A-17 is on its way, t...
// [slack #sec] *SECURITY* NEW LOGIN FROM UNKNOWN DEVICE
}Laravel: notifications are Bridge-like. A notification decides what to say and via() picks channels at run time; a custom channel is a new implementor. The coupling that stops it from being a pure Bridge is that each notification needs a toMail(), toSms()… method per channel it supports.
<?php
// Bridge: notification kinds (abstraction) x delivery channels (implementor).
// Laravel's notification system is Bridge-like: a Notification says WHAT,
// a channel class says HOW, and via() connects them at runtime.
namespace App\Notifications;
use App\Notifications\Channels\SmsChannel;
use App\Notifications\Messages\SmsMessage;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
final class OrderShipped extends Notification implements ShouldQueue
{
use Queueable;
public function __construct(public string $orderId, public string $tracking) {}
/** The bridge: pick implementors per recipient, at runtime. */
public function via(object $notifiable): array
{
return $notifiable->prefers_sms ? [SmsChannel::class] : ['mail', 'database'];
}
public function toMail(object $notifiable): MailMessage
{
return (new MailMessage)
->subject('Order shipped')
->line("Order {$this->orderId} is on its way, tracking {$this->tracking}.");
}
public function toSms(object $notifiable): SmsMessage
{
return new SmsMessage("Order {$this->orderId} shipped: {$this->tracking}");
}
/** @return array<string, string> */
public function toArray(object $notifiable): array
{
return ['order_id' => $this->orderId, 'tracking' => $this->tracking];
}
}
namespace App\Notifications\Messages;
final class SmsMessage
{
public function __construct(public string $text) {}
}
// A custom channel is one implementor; every notification that has toSms() can use it.
namespace App\Notifications\Channels;
use App\Notifications\Sms\SmsSender;
use Illuminate\Notifications\Notification;
final class SmsChannel
{
public function __construct(private SmsSender $sender) {} // the Adapter from Adapter.php
public function send(object $notifiable, Notification $notification): void
{
$message = $notification->toSms($notifiable);
$this->sender->send($notifiable->routeNotificationFor('sms'), $message->text);
}
}
// The coupling that makes it "Bridge-like" rather than a pure Bridge:
// each notification must know a toX() method per channel it supports, so adding
// a channel can require touching notifications. A pure Bridge has one implementor
// interface (e.g. deliver(to, subject, body)) that every abstraction uses unchanged.Consequences: the two sides evolve and are tested separately; implementations can be chosen at run time (config, tenant, feature flag); the class count grows additively, not multiplicatively. The cost: you must find the right Implementor interface up front, and a too-small one forces every abstraction to work around it (the toX() methods above); for a single dimension it is pure overhead.
When not to use: when only one dimension varies (that is just an interface + implementations, i.e. Strategy or DIP); when you do not yet know the second dimension (wait; refactor to Bridge when the second variant shows up).
Flyweight Good to know
In plain words: when you have a huge number of objects that each carry the same heavy data, keep one shared copy of that data and give each object only a pointer plus its own small, unique data. The one map design for 10,000 hotel guests.
Common misunderstanding: "Flyweight is a cache." A cache keeps results to avoid recomputing; a flyweight keeps shared immutable state to avoid duplicating memory. Refactoring.guru's applicability rule is blunt: "Use the Flyweight pattern only when your program must support a huge number of objects which barely fit into available RAM."
Definition (GoF intent): "Use sharing to support large numbers of fine-grained objects efficiently." The key distinction: intrinsic state "is stored in the flyweight; it consists of information that's independent of the flyweight's context, thereby making it sharable"; extrinsic state "depends on and varies with the flyweight's context and therefore can't be shared", so the client stores it and passes it in.
Problem: a map with 100,000 markers, each with a 4 KiB icon: 390 MiB of identical bitmaps. A text editor with one object per character, each with font metrics. A service holding millions of rows each with a repeated string like "eu-west-1/orders/v2".
| Participant | Role | In the snippet |
|---|---|---|
| Flyweight | Holds intrinsic state; must be immutable | MarkerStyle |
| FlyweightFactory | Creates and hands out shared flyweights | StyleFactory.Get, MarkerStyleFactory::for, unique.Make |
| Context (client) | Holds extrinsic state + a reference to a flyweight | Marker{Lat, Lng, Style} |
Loop i Factory.Get(kind) Heap
1 i = 0 "cafe" not in map → new MarkerStyle +4 KiB
2 i = 1 "atm" not in map → new MarkerStyle +4 KiB
3 i = 2.. found → return the same pointer +24 B per Marker (lat, lng, pointer)
4 100,000 markers: measured +2.3 MiB heap, vs ~390 MiB if each Marker copied its iconReal scenarios: string interning (Go's unique.Make, Java's String.intern, PHP's interned strings in OPcache); glyph and font caches in text rendering; game sprites and tiles; map markers and chart styles; enum-like objects (PHP enums: "each case is backed by a singleton object"); shared immutable configuration objects referenced by millions of entities; time.Location values shared by every time.Time in Go.
Go: a hand-written factory with a mutex-guarded map, and the standard library's unique package. The Go blog explains that unique keeps entries only while handles exist: "when the canonical entries are no longer being used, then the garbage collector is free to clean them up."
// Flyweight: share the intrinsic (context-free) part of many small objects
// and pass the extrinsic part in. Two Go forms: a hand-written factory with
// a map, and the standard library's unique package (Go 1.23+).
package main
import (
"fmt"
"runtime"
"sync"
"unique"
)
// Intrinsic state: identical for every map marker of the same kind.
type MarkerStyle struct {
Icon [4096]byte // pretend this is a decoded 4 KiB bitmap
Color string
Label string
}
// Flyweight factory: one shared *MarkerStyle per kind.
type StyleFactory struct {
mu sync.Mutex
styles map[string]*MarkerStyle
}
func (f *StyleFactory) Get(kind string) *MarkerStyle {
f.mu.Lock()
defer f.mu.Unlock()
if s, ok := f.styles[kind]; ok {
return s
}
s := &MarkerStyle{Color: map[string]string{"cafe": "brown", "atm": "green"}[kind], Label: kind}
f.styles[kind] = s
return s
}
// Context object: extrinsic state (position) + a pointer to the flyweight.
type Marker struct {
Lat, Lng float64
Style *MarkerStyle
}
func heapMB() float64 {
var m runtime.MemStats
runtime.GC()
runtime.ReadMemStats(&m)
return float64(m.HeapAlloc) / (1 << 20)
}
func main() {
f := &StyleFactory{styles: map[string]*MarkerStyle{}}
kinds := []string{"cafe", "atm"}
before := heapMB()
markers := make([]Marker, 100_000)
for i := range markers {
markers[i] = Marker{Lat: float64(i) / 1e3, Lng: 51.4, Style: f.Get(kinds[i%2])}
}
fmt.Printf("100k markers share %d styles, heap +%.1f MiB (without sharing: ~%d MiB of icons)\n",
len(f.styles), heapMB()-before, 100_000*4096>>20)
// unique.Make interns comparable values: equal values -> equal handles,
// and comparing handles is a pointer comparison.
a := unique.Make("eu-west-1/orders/v2")
b := unique.Make("eu-west-1/orders/" + "v2")
fmt.Println(a == b, a.Value())
runtime.KeepAlive(markers)
// Output:
// 100k markers share 2 styles, heap +2.3 MiB (without sharing: ~390 MiB of icons)
// true eu-west-1/orders/v2
}Laravel / PHP: enum cases as flyweights, a static pool for heavier shared data, and the lifetime warning that matters under Octane.
<?php
namespace App\Map;
// 1) Enum cases are shared singleton objects: a built-in flyweight.
enum MarkerKind: string
{
case Cafe = 'cafe';
case Atm = 'atm';
case Pharmacy = 'pharmacy';
// Intrinsic state lives on the case, computed, never copied per marker.
public function color(): string
{
return match ($this) {
self::Cafe => '#8B4513',
self::Atm => '#2E8B57',
self::Pharmacy => '#C0392B',
};
}
public function icon(): string
{
return "icons/{$this->value}.svg";
}
}
// 2) A hand-written flyweight factory for heavier intrinsic state.
final class MarkerStyle
{
public function __construct(
public readonly string $color,
public readonly string $svg, // e.g. 6 KB of SVG markup, loaded once
) {}
}
final class MarkerStyleFactory
{
/** @var array<string, MarkerStyle> */
private static array $pool = [];
public static function for(MarkerKind $kind): MarkerStyle
{
return self::$pool[$kind->value] ??= new MarkerStyle(
$kind->color(),
(string) file_get_contents(public_path($kind->icon())),
);
}
}
// Context object: extrinsic state (lat/lng) + a reference to the shared flyweight.
final class Marker
{
public function __construct(
public readonly float $lat,
public readonly float $lng,
public readonly MarkerStyle $style,
) {}
}
// 50,000 markers, 3 MarkerStyle objects:
// $markers = $places->map(fn ($p) => new Marker($p->lat, $p->lng, MarkerStyleFactory::for($p->kind)));
// MarkerKind::Cafe === MarkerKind::from('cafe'); // true: the same object
//
// Lifetime note: under PHP-FPM the static pool lives for one request; under
// Laravel Octane it lives for the whole worker, so only pool immutable data.Consequences: large memory savings when the shared part is big and the number of objects is huge; equality checks become pointer comparisons. The cost: code complexity (state is split in two); the flyweight must be immutable, or one change appears in 100,000 places; the factory needs locking under concurrency; "lifetime" becomes a question (a static pool in Laravel Octane lives as long as the worker).
When not to use: when you have thousands of objects, not millions; when the shared part is small (a pointer is 8 bytes; sharing a 16-byte struct saves nothing); before you have measured memory.
Telling the wrappers apart
The structure diagrams of Adapter, Proxy and Decorator are nearly identical: an object that implements an interface and holds a reference to another object. GoF's whole discussion section exists because "the similarities belie the different intents". The table is the version to keep.
| Adapter | Bridge | Decorator | Proxy | Facade | |
|---|---|---|---|---|---|
| Intent in one line | Make an existing interface fit | Split two dimensions | Add responsibilities, stackably | Control access to one subject | Simplify a subsystem |
| Interface the client sees | The Target (different from the adaptee) | The abstraction's | Same as the component | Same as the subject | New, higher-level |
| Wraps | One adaptee | One implementor (by reference) | One component | One subject | Many objects |
| Stacked? | Rarely | No | Yes, by design | Rarely ("not designed for recursive composition", GoF) | No |
| Who creates the wrapped object | Usually the caller passes it | Configured at construction | The caller, then wraps | Often the proxy itself (virtual proxy) | The facade or the container |
| Designed when | After the fact | Before the hierarchies grow | Any time | Any time | Any time |
| Go example | http.HandlerFunc, SDK adapter | database/sql × driver | bufio.Writer, middleware | httputil.ReverseProxy, sync.OnceValues | http.Get |
| Laravel example | Cache stores, Flysystem adapters | Notification × channel | Middleware, Container::extend | Laravel facades, lazy proxies | A service class over SDK calls |
| Network-scale twin | Anti-corruption layer, protocol translator | Pluggable transport in a client library | Sidecar adding mTLS/retries | Reverse proxy, CDN, sidecar | API gateway, BFF |
Combinations you will meet. An API gateway is a Facade (one entry, aggregation) and a Proxy (auth, caching, routing). An anti-corruption layer is an Adapter (implements your port) plus a Facade (one call instead of a protocol) plus a translator. A sidecar is a Proxy that often behaves like a Decorator (adds mTLS, retries, metrics). A caching decorator and a caching proxy are the same code; call it a decorator if it is one layer in a stack the caller assembles, a proxy if it stands in for the subject and owns access to it.
Per-language and per-framework view
| Pattern | Go | Laravel / PHP | Java | .NET (C#) | TypeScript / Node | Python |
|---|---|---|---|---|---|---|
| Facade | Package-level funcs (http.Get) | Service class; not Illuminate\Support\Facades | Session Facade (Core J2EE Patterns) over EJBs | Service classes | Module index.ts exporting a small API | Module-level API (requests.get) |
| Adapter | Implicit interfaces, HandlerFunc | Store, Flysystem, PSR-18 clients | InputStreamReader (bytes → chars) | StreamReader | Wrapper classes over SDKs | Wrapper classes, io.TextIOWrapper |
| Composite | Structs holding []Interface | Rule objects, component trees | AWT/Swing Container | WPF visual tree | React/DOM trees | ast module nodes |
| Proxy | ReverseProxy, OnceValues | Facades, newLazyProxy, Doctrine proxies | java.lang.reflect.Proxy, Spring AOP proxies | DispatchProxy, EF Core lazy-loading proxies | ES Proxy object | __getattr__ forwarding |
| Decorator | bufio, gzip, middleware | Middleware, extend, Guzzle middleware | BufferedInputStream, Collections.synchronizedList | BufferedStream, GZipStream | Express/Koa middleware | WSGI middleware; @functools.wraps functions |
| Bridge | database/sql × driver, slog × Handler | Notifications × channels, Storage × adapter | JDBC DriverManager × driver | ADO.NET providers | Knex dialect clients | DB-API drivers |
| Flyweight | unique.Make | Enum cases, interned strings | Integer.valueOf cache, String.intern | String interning | Interned strings in V8 | Small-int cache, sys.intern |
Mechanics
Go: explicit forwarding, embedding and interface satisfaction Must-know
A Go wrapper is a struct that holds the wrapped value and has the right methods. Two styles:
// Explicit forwarding: every method is written out. Safe; nothing leaks.
type countingWriter struct{ w io.Writer; n int64 }
func (c *countingWriter) Write(p []byte) (int, error) { n, err := c.w.Write(p); c.n += int64(n); return n, err }
// Embedding: the wrapper promotes every method of the embedded value and overrides some.
type statusRecorder struct {
http.ResponseWriter // Header() and Write() are promoted unchanged
status int
}
func (r *statusRecorder) WriteHeader(code int) { r.status = code; r.ResponseWriter.WriteHeader(code) }Embedding is shorter, but it promotes only the methods of the embedded static type. If you embed an http.ResponseWriter, the wrapper has Header, Write and WriteHeader, and not Flush, Hijack or ReadFrom, even when the dynamic value has them (see Structs, methods & embedding and Interfaces). Add var _ Target = (*Adapter)(nil) lines to catch a missing method at compile time.
Lost optional interfaces and Unwrap Important
Many Go APIs check for an optional interface with a type assertion. A decorator hides it:
| Optional interface | Who checks for it | What breaks when hidden by a wrapper |
|---|---|---|
io.WriterTo / io.ReaderFrom | io.Copy: "If src implements WriterTo, the copy is implemented by calling src.WriteTo(dst). Otherwise, if dst implements ReaderFrom…" | Fast paths such as sendfile from an *os.File are lost; copies go through a buffer |
http.Flusher | Streaming handlers, SSE | w.(http.Flusher) fails, server-sent events stop streaming |
http.Hijacker | WebSocket upgraders | The type assertion fails and the WebSocket upgrade returns an error |
io.Closer | Callers that close the outermost value | gzip.Writer is not flushed, or the underlying file is not closed |
The Go 1.20 fix is http.NewResponseController(w): "The ResponseWriter should be the original value passed to the Handler.ServeHTTP method, or have an Unwrap method returning the original ResponseWriter." So every ResponseWriter decorator you write should have func (r *statusRecorder) Unwrap() http.ResponseWriter, as the decorator snippet does.
Order and close order of decorators Must-know
Wrapping order is execution order; the outermost layer runs first and finishes last. For writers, flushing goes from outside in: in bufio.NewWriter(gzip.NewWriter(file)) you must Flush the bufio.Writer, then Close the gzip.Writer (which writes the gzip footer), then close the file. Close only the innermost and you get a truncated archive with no error.
Chain A: Logging(Metrics(Retry(client))) Chain B: Retry(Logging(client))
1 one log line per logical call one log line per attempt
2 metrics: requests 1, failures 0 metrics (if inside): requests 3, failures 2
3 good for "what did the user experience" good for "how flaky is the dependency"
4 measured in the lab: A logs 1 line, B logs 3 lines (503, 503, 200)Laravel's HTTP client puts its retry() loop around the whole Guzzle handler stack (in the 13.x source, PendingRequest::send wraps each sendRequest(...) call, which runs the Guzzle client and its middleware, in the retry() helper), so Guzzle middleware registered with withMiddleware runs once per attempt, like chain B.
The RoundTripper contract and where retries belong Important
http.RoundTripper looks like the perfect decorator point for clients, and for logging, tracing and auth headers it is. But its documentation sets rules: "RoundTrip should not attempt to interpret the response", "RoundTrip should not modify the request, except for consuming and closing the Request's Body", and "RoundTrip must always close the body, including on errors". A retry that inspects status codes interprets the response, and a header-adding decorator must req.Clone(ctx) first. That is why the lab decorates a small Doer interface (Do(*http.Request) (*http.Response, error), which *http.Client already satisfies) instead. A retry decorator must also: re-create the body with Request.GetBody (set automatically by http.NewRequest for common body types) and refuse to retry when it is nil, drain and close a failed response before retrying so the connection is reused, stop on ctx.Done(), and refuse to replay non-idempotent requests without an idempotency key (see Timeouts, Retries & Jitter and API Idempotency). Note that Transport already retries some failures itself: it "only retries a request upon encountering a network error if the connection has already been used successfully and if the request is idempotent", and it treats a request with an Idempotency-Key header as idempotent; your decorator sits on top of that.
PHP: __call, __callStatic and the container Important
PHP can write generic proxies with magic methods: __call($method, $args) forwards any instance call, __callStatic any static call. Laravel's Facade uses the static one; Macroable uses both to add methods at run time (and re-binds macro closures to the target class: $macro->bindTo($this, static::class), which is why self:: inside a macro does not mean your class). The cost of magic forwarding: no static analysis or IDE completion without @method docblocks, and every call goes through a dynamic dispatch.
Container::extend($abstract, $closure) is Laravel's decorator hook. From the 13.x source: if the service is already resolved as a shared instance, the closure is applied immediately and the binding is "rebound"; otherwise the closure is queued in $extenders[$abstract] and applied every time the service is resolved. Multiple extend calls stack in registration order, so the last one is the outermost layer.
PHP 8.4 lazy objects Good to know
PHP 8.4 makes virtual proxies a language feature. ReflectionClass::newLazyGhost() creates an object of the real class whose initialiser fills it in place; newLazyProxy() creates a proxy whose factory returns a separate real instance, after which property accesses are forwarded to it. Both trigger on first access to the object's state, not on construction. The PHP manual's caveat applies to proxies: the proxy and the real instance are two objects, so identity checks (===) can surprise you.
Identity, equality and type checks Important
GoF on Decorator: "a decorated component is not identical to the component itself. Hence you shouldn't rely on object identity when you use decorators." The same holds for proxies. In Go, a type switch on *os.File fails if the file is wrapped; errors.As works through wrapped errors only because errors implement Unwrap. In PHP, instanceof EloquentCatalog fails on the caching proxy. Flyweight is the opposite case: it relies on identity (one pointer per kind, MarkerKind::Cafe === MarkerKind::from('cafe')).
Performance: what wrapping costs, measured Good to know
Measured with the benchmark in the snippets (go test -bench . -benchmem ./bench, Go 1.27, Apple M5). Treat the numbers as orders of magnitude for your own machine, not as constants.
| Benchmark | ns/op | B/op | allocs/op | What it shows |
|---|---|---|---|---|
| Direct method call | 0.24 | 0 | 0 | Baseline |
| Call through an interface | 0.25 | 0 | 0 | Same as direct: the compiler devirtualised the call (-gcflags=-m prints "devirtualizing p.Price to base") |
| Five stacked decorators, built once | 3.56 | 0 | 0 | About 0.7 ns per layer of interface dispatch |
| Five decorators built on every call | 35.08 | 80 | 5 | Each &fee{...} escapes to the heap: build chains once, at startup |
Rules that follow: build decorator chains once (in main or a service provider), not per request; avoid per-call closures in hot paths; a buffered decorator (bufio) usually saves far more (fewer syscalls) than its dispatch costs; in PHP-FPM every request rebuilds the container, so a deep extend chain is paid on every request, while under Octane it is paid once per worker.
Go
The Go angle
Go has no classes and no inheritance, so every structural pattern is the object form: a struct (or a function type) that holds an interface value. Three language features do most of the work. Implicit interfaces mean a third-party type may already satisfy your port, so many adapters are unnecessary. Function types with methods (http.HandlerFunc, the lab's DoerFunc) turn a closure into an interface value, which makes decorators one-liners. Embedding gives cheap partial forwarding, with the caveat in Mechanics.
| Pattern | Standard library instance | What to notice |
|---|---|---|
| Decorator | bufio.NewReader/Writer, gzip.NewReader/Writer, io.TeeReader, io.LimitReader, cipher.StreamReader | Same interface in and out; flush and close from the outside in |
| Decorator | http.StripPrefix, http.TimeoutHandler, http.MaxBytesHandler | Standard middleware: func(Handler, …) Handler |
| Adapter | http.HandlerFunc, io.NopCloser, strings.NewReader, bytes.NewReader | A function or a value adapted to an interface |
| Composite | io.MultiWriter, io.MultiReader, errors.Join | One value that stands for many of the same interface |
| Proxy (remote) | httputil.ReverseProxy with Rewrite, SetURL, SetXForwarded, ModifyResponse | "an HTTP Handler that takes an incoming request and sends it to another server" |
| Proxy (virtual) | sync.Once, sync.OnceValue, sync.OnceValues | Build on first use, exactly once, safe for concurrent callers |
| Bridge | database/sql × database/sql/driver; log/slog.Logger × slog.Handler | Front-end API and back-end implementations vary independently |
| Flyweight | unique.Make / unique.Handle[T] | Interning; equal handles compare as pointers |
| Facade | http.Get, http.Post, os.ReadFile | One call over a client, a transport, a file and its buffer |
Two Go-specific rules. First, keep ports small: an adapter for a two-method interface is easy to write and to fake, while an adapter for a twenty-method interface is a project (Interface Segregation). Second, define the interface where it is used, not where it is implemented, so the adapter depends on your package and not the other way round (Dependency Inversion). The Go pages on io readers and writers and middlewares go deeper into the two biggest decorator families.
Laravel
The Laravel angle
Laravel is built from structural patterns, and some of its names collide with the GoF names. This is the map.
| Laravel feature | GoF pattern | Evidence (Laravel 13 docs or source) |
|---|---|---|
Illuminate\Support\Facades\* | Proxy (+ Service Locator), not Facade | "Laravel facades serve as "static proxies" to underlying classes in the service container" |
Real-time facades (use Facades\App\…) | Proxy generated on demand | "you may treat any class in your application as if it was a facade" |
| HTTP middleware | Decorator + Chain of Responsibility | "a series of "layers" HTTP requests must pass through"; can reject the request |
$this->app->extend() | Decorator registration | "you may run additional code to decorate or configure the service" |
Cache stores, Cache::extend | Adapter (to Illuminate\Contracts\Cache\Store) | "we first need to implement the Illuminate\Contracts\Cache\Store contract" |
Storage + Flysystem, Storage::extend | Adapter, and Bridge (disk API × adapter) | "simple drivers for working with local filesystems, SFTP, and Amazon S3… the API remains the same" |
HTTP client withMiddleware, withRequestMiddleware, withResponseMiddleware, globalRequestMiddleware | Decorator (Guzzle middleware) | "Since Laravel's HTTP client is powered by Guzzle, you may take advantage of Guzzle Middleware" |
Http::macro, Macroable | Not a GoF pattern: run-time method addition | Http::macro('github', …) in the docs |
Notifications via() + channels | Bridge-like | "write your own drivers to deliver notifications via other channels"; a custom channel is "a class that contains a send method" |
| Eloquent relationships (lazy) | Lazy Load (proxy-like) | "Dynamic relationship properties perform "lazy loading"" |
Model::preventLazyLoading() | A guard against the proxy's hidden cost | "instruct Laravel to always prevent the lazy loading of relationships" |
Rule objects (ValidationRule), arrays of rules | Composite (a rule made of rules) | validate(string $attribute, mixed $value, Closure $fail) |
| PHP 8.1 enums | Flyweight | "each case is backed by a singleton object of that name" (PHP manual) |
PHP 8.4 newLazyProxy / newLazyGhost | Virtual proxy | "Ghost Objects and Virtual Proxies" (PHP manual) |
PSR standards make these adapters and decorators portable across frameworks: PSR-7 messages are immutable (so a decorator returns a modified copy, $request->withHeader(...)), PSR-15 defines server middleware and request handlers, and PSR-18 defines ClientInterface::sendRequest(), which every HTTP client adapter implements. PSR-18 also warns decorator authors that the request a client sends "MAY be a different object from the one passed to ClientInterface::sendRequest()", so never compare requests with === across a middleware chain.
Solving the classic problems
| Problem | Pattern(s) | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| Vendor SDK types everywhere | Adapter (+ ACL) | Own port; one adapter per vendor | Swap vendor, fake in tests | Translation may lose detail |
| Same cross-cutting code in every client call | Decorator | Logging, metrics, retry, auth as layers | One class per concern, any order | Order bugs, long stack traces |
| Slow or remote dependency | Proxy (caching, virtual) | Cache-aside wrapper, lazy init | No caller changes | Staleness, invalidation |
| N+1 queries | Proxy gone wrong (lazy loading) | Eager-load, preventLazyLoading | Predictable query count | Must know access patterns |
| Class explosion (kinds × channels) | Bridge | Two hierarchies + a reference | Additive growth | Implementor interface must be right |
| Tree data handled with type checks | Composite | One interface for leaf and group | Simple clients | Hard to restrict child types |
| Memory blow-up from duplicates | Flyweight | Share immutable intrinsic state | Large RAM savings | Split state, immutability rules |
| Controllers orchestrating five services | Facade | One use-case class | One place for order and compensation | Can become a god class |
Vendor lock-in and the anti-corruption layer
An adapter translates one interface. When the other side has a different model (other names, units, states, error codes), you need an anti-corruption layer: Azure's description is "a facade or adapter layer between different subsystems that don't share the same semantics. This layer translates requests that one subsystem makes to the other subsystem." In code it is three parts: a port your domain owns, a translator that maps both directions, and an adapter/facade that implements the port with one call. The lab builds one. Strategic context (conformist vs ACL vs open host) is on Context Maps & Integration Patterns; the migration story (an ACL is how a strangler fig talks to the old system) is on its own page.
-- The legacy side often shows up as a schema too. Map it in ONE place (a view or the translator),
-- never by letting domain code read legacy columns.
CREATE VIEW payments_v AS
SELECT txn_ref AS payment_id,
CAST(amt_str AS BIGINT) AS amount_minor, -- '000001500000' → 1500000
cur AS currency,
CASE rc WHEN '00' THEN 'approved'
WHEN '51' THEN 'declined_insufficient_funds'
WHEN '62' THEN 'declined_card_blocked'
ELSE 'unknown' END AS status
FROM legacy_pay_txn;Cross-cutting concerns without inheritance
Use decorators for concerns that apply to every call of an interface (logging, metrics, tracing, retries, timeouts, auth headers, caching), and keep business rules out of them. Build the chain in one place (Go main, a Laravel service provider via extend, a Guzzle stack via the Http::macro). Name the order explicitly in a comment; the order is part of the design (see Order of decorators).
Lazy loading and N+1
Every virtual proxy has the same failure mode: the caller cannot see the cost, so it calls it in a loop. For Eloquent: eager-load with with(), enable Model::preventLazyLoading() outside production, and watch the query count in tests. For Go: do not hide a network call behind a method that looks like a field accessor; take a context.Context so the cost is visible in the signature.
Class explosion
When names look like PdfInvoiceReport, CsvInvoiceReport, PdfSalesReport, CsvSalesReport, you have two dimensions in one hierarchy. Extract the second dimension into an interface (the Implementor) and hold it by reference (Bridge). If only one dimension really varies, a plain interface with implementations (Strategy, DIP) is enough.
Choosing
| Situation | Use | Extra technique | Reason |
|---|---|---|---|
| A vendor SDK must not leak | Adapter behind your own port | Contract tests against the port | Replaceable, testable |
| Another system with a different model | Anti-corruption layer (Adapter + Facade + translator) | Map errors to domain errors; keep it in one module | Protects your model from theirs |
| Controllers repeat a multi-step workflow | Facade (a use-case or service class) | Keep it small; one per use case | One place for order and compensation |
| Logging/metrics/retry around a client | Decorator chain | Build once at startup; document order | Composable, testable layers |
| Expensive object, rarely used | Virtual proxy | sync.OnceValues, PHP 8.4 newLazyProxy | Faster boot |
| Repeated reads of slow data | Caching proxy | TTL + explicit invalidation; Caching | Fewer queries/calls |
| Authorization tied to an object | Protection proxy, or a policy at the edge | Laravel Policies / Gates | Uniform enforcement |
| Calls to another service | Remote proxy (client stub, reverse proxy) | Timeouts, retries, circuit breaker as decorators | Location transparency, carefully |
| Tree of things with one operation | Composite | Safety-style Add on the composite only | Uniform clients |
| Two dimensions both grow | Bridge | Design the implementor interface first | Additive growth |
| Millions of similar objects | Flyweight | Measure memory first; unique.Make | RAM |
| Want to rename Laravel facades "facades" in a design doc | Call them static proxies | Inject dependencies in domain code | Accurate vocabulary |
In architecture: from a single process to a distributed system
The seven patterns keep their shape as the boxes get bigger; what changes is that the arrows become network calls that can fail, be slow, or be retried.
Monolith: one process, one database
How it shows up: classes and functions. Facades are service or use-case classes; adapters wrap vendor SDKs; decorators are middleware and extend; proxies are caching repositories and lazy services; composites are menus, rules and component trees.
Simplest correct usage: wire everything in one composition root (Go main, Laravel service providers) so the structure is visible in one file; type-hint ports, not vendors.
Example (simple): a blog that sends email through MailSender, implemented by an adapter around a provider SDK, decorated with logging via extend.
Example (complex): a shop where checkout calls CheckoutFacade::placeOrder, which uses Inventory, a PaymentGateway port implemented by LegacyPayGateway (the ACL) and wrapped in logging and metrics decorators, while the catalog sits behind a caching proxy.
Modular monolith: modules, boundaries, one deployable
How it shows up: each module exposes a facade (its public API) and hides the rest. Other modules call only the facade; this is the facade used as a boundary, not just a convenience. Cross-module calls are where you place adapters when two modules use different models, so one module's vocabulary does not leak into another. See Modular Monolith.
billing module catalog module (public facade only)
1 Billing\InvoiceTotals ─────────────▶ Catalog\CatalogApi::priceOf($sku) (facade)
2 internal: PriceRepository, Discounts, Currency (hidden)
3 architecture test: billing may import Catalog\CatalogApi, never Catalog\Internal\*Microservices: patterns with a network in between
API gateway = Facade + Proxy. A single entry point for clients (Facade), routing and offloading auth, TLS, rate limits and caching (Proxy); Azure lists "Gateway routing", "Gateway aggregation" and "Gateway offloading". Aggregation is the facade part; routing and offloading are the proxy part. Details on API Gateway, BFF & Service Mesh.
Anti-corruption layer = Adapter + Facade. Between your service and a legacy or third-party system with a different model. It can be a module inside your service or its own service; Azure notes it "adds latency to calls between the two systems".
Sidecar = an out-of-process Proxy (often acting as a Decorator). Envoy or a mesh proxy next to each instance adds mTLS, retries, timeouts and metrics without code changes. Same interface for the app (it still makes an HTTP call), more behaviour on the path. See Service Mesh & the Sidecar Pattern.
Client decorators. Retries with jitter, timeouts, circuit breakers and bulkheads wrap every outbound client. Put them in a decorator chain built once; decide whether metrics sit inside or outside the retry; never retry non-idempotent calls without an idempotency key. See Timeouts, Retries & Jitter and Circuit Breaker.
Client app ──▶ API gateway (facade: aggregate /checkout; proxy: JWT check, rate limit)
1 ├──▶ orders-svc (sidecar proxy: mTLS, retry 2x on 503)
2 └──▶ payments-svc
3 client: Logging(Metrics(Breaker(Retry(http.Client))))
4 ──▶ ACL (adapter + translator) ──▶ legacy switch "RC=51" → ErrInsufficientFundsDistributed data: caches, CDNs and remote proxies
Caching proxies at every layer: in-process maps, Redis (cache-aside), HTTP caches and CDNs (reverse proxies that cache). Each is a proxy that trades freshness for latency; the hard part is invalidation and stampedes (Caching, CDNs). Remote proxies hide distance, and distance is where the fallacies of distributed computing live: the network is not reliable, latency is not zero. A remote proxy should make failure visible (errors, context.Context, timeouts), not pretend to be a local object. Flyweight across processes becomes a shared reference-data service or a CDN-hosted asset: one copy, referenced by ID.
Scaling path: 1×, 10×, 100×
| Scale | Structure | Structural-pattern practice |
|---|---|---|
| 1× (one app) | Monolith | Adapters for vendors, a few facades, middleware; one composition root |
| 10× (several teams, one repo) | Modular monolith | Module facades as boundaries; ACLs between modules with different models; decorators for metrics on every port |
| 100× (many services) | Services + gateway + mesh | Gateway (facade + proxy), sidecars, ACLs at service boundaries, client decorator chains with retries and breakers, CDN as a caching proxy |
Lab
Two labs, each with Go (runs offline) and Laravel (reviewed code). Everything uses httptest, so no network is needed.
Setup.
cd docs/snippets/design/structural-patterns/go
gofmt -l . && go vet ./... # no output from gofmt, vet cleanLab 1: a logging + metrics + retry decorator chain around an HTTP client
// Lab: a decorator chain around an HTTP client.
// Doer is the small interface *http.Client already satisfies; every
// decorator implements it too, so they stack in any order.
package main
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"os"
"strings"
"sync/atomic"
"time"
)
type Doer interface {
Do(*http.Request) (*http.Response, error)
}
type DoerFunc func(*http.Request) (*http.Response, error)
func (f DoerFunc) Do(r *http.Request) (*http.Response, error) { return f(r) }
// Logging: one line per call that passes through it.
func Logging(log *slog.Logger, layer string) func(Doer) Doer {
return func(next Doer) Doer {
return DoerFunc(func(r *http.Request) (*http.Response, error) {
resp, err := next.Do(r)
status := 0
if resp != nil {
status = resp.StatusCode
}
log.Info(layer, "method", r.Method, "url", r.URL.Path, "status", status, "err", err)
return resp, err
})
}
}
// Metrics: counters a real system would export to Prometheus or OTel.
type Metrics struct{ Requests, Failures atomic.Int64 }
func (m *Metrics) Wrap(next Doer) Doer {
return DoerFunc(func(r *http.Request) (*http.Response, error) {
m.Requests.Add(1)
resp, err := next.Do(r)
if err != nil || resp.StatusCode >= 500 {
m.Failures.Add(1)
}
return resp, err
})
}
// Retry: replays idempotent requests on transport errors, 502, 503 and 504.
func Retry(attempts int, base time.Duration) func(Doer) Doer {
return func(next Doer) Doer {
return DoerFunc(func(r *http.Request) (*http.Response, error) {
if r.Method != http.MethodGet && r.Header.Get("Idempotency-Key") == "" {
return next.Do(r) // never blindly replay a non-idempotent call
}
if r.Body != nil && r.Body != http.NoBody && r.GetBody == nil {
return next.Do(r) // body cannot be replayed: one attempt only
}
var lastErr error
for i := range attempts {
req := r.Clone(r.Context()) // a RoundTripper must not see a mutated request
if r.Body != nil && r.GetBody != nil {
body, err := r.GetBody() // fresh copy of the body for every attempt
if err != nil {
return nil, err
}
req.Body = body
}
resp, err := next.Do(req)
if err == nil && !retryable(resp.StatusCode) {
return resp, nil
}
if err == nil {
io.Copy(io.Discard, resp.Body) // drain so the connection is reused
resp.Body.Close()
lastErr = fmt.Errorf("status %d", resp.StatusCode)
} else {
lastErr = err
}
if i == attempts-1 {
break
}
select { // exponential backoff that honours cancellation
case <-time.After(base << i):
case <-r.Context().Done():
return nil, r.Context().Err()
}
}
return nil, fmt.Errorf("after %d attempts: %w", attempts, lastErr)
})
}
}
func retryable(code int) bool {
return code == http.StatusBadGateway || code == http.StatusServiceUnavailable || code == http.StatusGatewayTimeout
}
// Chain applies the first decorator outermost.
func Chain(d Doer, ds ...func(Doer) Doer) Doer {
for i := len(ds) - 1; i >= 0; i-- {
d = ds[i](d)
}
return d
}
func main() {
var hits atomic.Int64
flaky := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if hits.Add(1)%3 != 0 { // fails twice, then succeeds
http.Error(w, "busy", http.StatusServiceUnavailable)
return
}
fmt.Fprint(w, "paid")
}))
defer flaky.Close()
log := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey {
return slog.Attr{}
}
return a
},
}))
base := &http.Client{Timeout: 2 * time.Second}
m := &Metrics{}
// A: logging and metrics OUTSIDE retry: one log line per logical call.
outer := Chain(base, Logging(log, "outer"), m.Wrap, Retry(3, 10*time.Millisecond))
// B: logging INSIDE retry: one log line per attempt.
inner := Chain(base, Retry(3, 10*time.Millisecond), Logging(log, "attempt"))
for _, c := range []Doer{outer, inner} {
req, _ := http.NewRequestWithContext(context.Background(), "GET", flaky.URL+"/charge", nil)
resp, err := c.Do(req)
if err != nil {
fmt.Println("error:", err)
continue
}
b, _ := io.ReadAll(resp.Body)
resp.Body.Close()
fmt.Println("body:", strings.TrimSpace(string(b)))
}
fmt.Println("metrics (chain A): requests", m.Requests.Load(), "failures", m.Failures.Load())
// Cancellation wins over retry.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Millisecond)
defer cancel()
down := Chain(DoerFunc(func(*http.Request) (*http.Response, error) {
return nil, errors.New("connection refused")
}), Retry(5, 50*time.Millisecond))
req, _ := http.NewRequestWithContext(ctx, "GET", "http://payments.internal/charge", nil)
_, err := down.Do(req)
fmt.Println("with deadline:", err)
// Output:
// level=INFO msg=outer method=GET url=/charge status=200 err=<nil>
// body: paid
// level=INFO msg=attempt method=GET url=/charge status=503 err=<nil>
// level=INFO msg=attempt method=GET url=/charge status=503 err=<nil>
// level=INFO msg=attempt method=GET url=/charge status=200 err=<nil>
// body: paid
// metrics (chain A): requests 1 failures 0
// with deadline: context deadline exceeded
}Run it.
go run ./lab/httpclient. Expected output (the time attribute is stripped for stable output):textlevel=INFO msg=outer method=GET url=/charge status=200 err=<nil> body: paid level=INFO msg=attempt method=GET url=/charge status=503 err=<nil> level=INFO msg=attempt method=GET url=/charge status=503 err=<nil> level=INFO msg=attempt method=GET url=/charge status=200 err=<nil> body: paid metrics (chain A): requests 1 failures 0 with deadline: context deadline exceededExplain the difference. Chain A logs once per logical call because logging sits outside retry; chain B logs every attempt. Metrics in chain A report 0 failures even though the server failed twice: the retry hid them. Move
m.WrapinsideRetryand expectrequests 3 failures 2.Break the body. Change the request to
POSTwith anIdempotency-Keyheader and the bodystrings.NewReader("amount=100"), and print the body on the server: all three attempts arrive withamount=100, becausehttp.NewRequestsetGetBodyand both our decorator and theTransportuse it to rewind. Now wrap the body asio.MultiReader(strings.NewReader("amount=100")), a typeNewRequestdoes not recognise, soGetBodyis nil. Delete theGetBody == nilguard inRetryand run: measured, the server receivesamount=100, then"", then"", and the call "succeeds" with an empty charge. Put the guard back: the decorator now makes one attempt and returns the 503.Remove the drain. Delete
io.Copy(io.Discard, resp.Body)and count new connections on the test server (httptest.NewUnstartedServer, setConfig.ConnState, thenStart()). Thenet/httpdocs warn that a body not "read to EOF and closed" means the Transport "may not be able to re-use a persistent TCP connection". In our run (Go 1.27, localhost, 5-byte and 64 KiB error bodies) the count stayed at 1 either way, so treat the drain as cheap insurance that this lab does not make visible.Laravel version. Register the macro from the snippet below and run the commented Pest test:
Http::assertSentCount(3), and threepayments.httplog lines, because Laravel'sretry()wraps the whole Guzzle stack (chain B).
<?php
// Lab: logging + metrics + retry around Laravel's HTTP client (Guzzle underneath).
namespace App\Providers;
use GuzzleHttp\Promise\Create;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Throwable;
final class PaymentsHttpServiceProvider extends ServiceProvider
{
/** In-process counters; export them to Prometheus/OTel in a real app. */
public static array $metrics = ['requests' => 0, 'failures' => 0];
public function boot(): void
{
// Build the decorators here: a macro closure is re-bound to the Http factory,
// so self:: inside it would no longer point at this provider.
$metrics = self::metrics();
$logging = self::logging();
// A macro gives the decorated client a name: Http::payments()->post(...).
Http::macro('payments', function () use ($metrics, $logging): PendingRequest {
return Http::baseUrl(config('services.payments.url'))
->timeout(3)
->acceptJson()
// Decorator 1: metrics (a full Guzzle middleware: handler -> handler).
->withMiddleware($metrics)
// Decorator 2: logging with duration.
->withMiddleware($logging)
// Decorator 3: a request-only decorator.
->withRequestMiddleware(fn (RequestInterface $r) => $r->withHeader('X-Client', 'shop/1.0'))
// Retry: Laravel loops around the WHOLE Guzzle stack, so the middleware
// above runs once per attempt (like chain B in the Go lab).
->retry(
3,
fn (int $attempt) => 100 * (2 ** ($attempt - 1)), // 100, 200, 400 ms
fn (Throwable $e, PendingRequest $request, ?string $method) =>
($method === 'GET' || isset($request->getOptions()['headers']['Idempotency-Key']))
&& ($e instanceof ConnectionException
|| ($e instanceof RequestException && in_array($e->response->status(), [502, 503, 504], true))),
);
});
}
private static function metrics(): callable
{
return fn (callable $handler) => function (RequestInterface $request, array $options) use ($handler) {
self::$metrics['requests']++;
return $handler($request, $options)->then(
function (ResponseInterface $response) {
if ($response->getStatusCode() >= 500) {
self::$metrics['failures']++;
}
return $response;
},
function ($reason) {
self::$metrics['failures']++;
return Create::rejectionFor($reason);
},
);
};
}
private static function logging(): callable
{
return fn (callable $handler) => function (RequestInterface $request, array $options) use ($handler) {
$start = hrtime(true);
return $handler($request, $options)->then(function (ResponseInterface $response) use ($request, $start) {
Log::info('payments.http', [
'method' => $request->getMethod(),
'path' => $request->getUri()->getPath(),
'status' => $response->getStatusCode(),
'ms' => intdiv(hrtime(true) - $start, 1_000_000),
]);
return $response;
});
};
}
}
// Test it without a network (tests/Feature/PaymentsClientTest.php):
//
// Http::fakeSequence('payments.test/*')
// ->pushStatus(503)->pushStatus(503)->push(['status' => 'paid'], 200);
// config(['services.payments.url' => 'https://payments.test']);
//
// $response = Http::payments()->get('/charges/42');
//
// expect($response->json('status'))->toBe('paid');
// Http::assertSentCount(3); // 2 retries + 1 success
// // Log has 3 "payments.http" lines: logging sits INSIDE the retry loop.Lab 2: an anti-corruption layer for a legacy payment API
// Lab: an anti-corruption layer (ACL) in front of a legacy payment API.
// Inside: our domain model (Money, ChargeResult, domain errors).
// Outside: a legacy gateway that speaks form posts, rial strings and
// two-digit response codes. The ACL is a facade (one call) built from an
// adapter (implements our port) and a translator (maps both models).
package main
import (
"context"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"strings"
"time"
)
// ===== our domain (no legacy words allowed in here) =====
type Money struct {
Minor int64 // smallest unit: cents, or rials for IRR
Currency string // ISO 4217
}
type ChargeResult struct {
PaymentID string
Approved bool
}
var (
ErrInsufficientFunds = errors.New("payment: insufficient funds")
ErrCardBlocked = errors.New("payment: card blocked")
ErrProviderDown = errors.New("payment: provider unavailable")
)
// Port: the interface our checkout depends on.
type PaymentGateway interface {
Charge(ctx context.Context, orderID string, amount Money) (ChargeResult, error)
}
// ===== the ACL =====
type LegacyPayACL struct {
baseURL string
merchantID string
http *http.Client
}
var _ PaymentGateway = (*LegacyPayACL)(nil)
// Translator, outbound: domain -> legacy wire format.
func toLegacy(merchant, orderID string, m Money) url.Values {
return url.Values{
"MERCHANT_ID": {merchant},
"AMT": {fmt.Sprintf("%012d", m.Minor)}, // zero-padded, 12 digits
"CUR": {m.Currency},
"REF": {strings.ToUpper(orderID)},
}
}
// Translator, inbound: legacy codes -> domain results and errors.
var legacyCodes = map[string]error{
"00": nil,
"51": ErrInsufficientFunds,
"62": ErrCardBlocked,
"91": ErrProviderDown,
}
func fromLegacy(body string) (ChargeResult, error) {
kv := map[string]string{}
for _, part := range strings.Split(strings.TrimSpace(body), ";") {
if k, v, ok := strings.Cut(part, "="); ok {
kv[k] = v
}
}
domainErr, known := legacyCodes[kv["RC"]]
if !known {
return ChargeResult{}, fmt.Errorf("payment: unknown legacy code %q", kv["RC"])
}
if domainErr != nil {
return ChargeResult{}, domainErr
}
return ChargeResult{PaymentID: "pay_" + kv["TXN"], Approved: true}, nil
}
func (a *LegacyPayACL) Charge(ctx context.Context, orderID string, amount Money) (ChargeResult, error) {
form := toLegacy(a.merchantID, orderID, amount)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, a.baseURL+"/cgi-bin/pay.exe",
strings.NewReader(form.Encode()))
if err != nil {
return ChargeResult{}, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := a.http.Do(req)
if err != nil {
return ChargeResult{}, fmt.Errorf("%w: %v", ErrProviderDown, err)
}
defer resp.Body.Close()
b, err := io.ReadAll(io.LimitReader(resp.Body, 4<<10)) // never trust legacy sizes
if err != nil {
return ChargeResult{}, err
}
return fromLegacy(string(b))
}
// ===== a fake legacy system for the lab =====
func legacyServer() *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = r.ParseForm()
amt, _ := strconv.ParseInt(r.PostForm.Get("AMT"), 10, 64)
switch {
case amt > 5_000_000:
fmt.Fprint(w, "RC=51;MSG=INSUFF FUNDS;TXN=0")
case r.PostForm.Get("REF") == "ORD-BLOCKED":
fmt.Fprint(w, "RC=62;MSG=RESTRICTED CARD;TXN=0")
default:
fmt.Fprintf(w, "RC=00;MSG=APPROVED;TXN=%s", r.PostForm.Get("REF"))
}
}))
}
func main() {
srv := legacyServer()
defer srv.Close()
var gw PaymentGateway = &LegacyPayACL{baseURL: srv.URL, merchantID: "M-001",
http: &http.Client{Timeout: 3 * time.Second}}
ctx := context.Background()
for _, tc := range []struct {
order string
minor int64
}{{"ord-1", 1_500_000}, {"ord-2", 9_000_000}, {"ord-blocked", 10}} {
res, err := gw.Charge(ctx, tc.order, Money{tc.minor, "IRR"})
switch {
case errors.Is(err, ErrInsufficientFunds):
fmt.Println(tc.order, "-> ask the customer for another card")
case err != nil:
fmt.Println(tc.order, "->", err)
default:
fmt.Println(tc.order, "->", res.PaymentID, res.Approved)
}
}
if _, err := fromLegacy("RC=05;MSG=DO NOT HONOR"); err != nil {
log.Println(err)
}
// Output:
// ord-1 -> pay_ORD-1 true
// ord-2 -> ask the customer for another card
// ord-blocked -> payment: card blocked
// <date> payment: unknown legacy code "05"
}Run it.
go run ./lab/acl. Expected:textord-1 -> pay_ORD-1 true ord-2 -> ask the customer for another card ord-blocked -> payment: card blocked <date> <time> payment: unknown legacy code "05"Find the boundary.
grep -n "RC\|AMT\|MERCHANT" lab/acl/main.go: every legacy word is inside the ACL section;main(the "checkout") only usesMoney,ChargeResultandErrInsufficientFunds.Add a code. The switch adds
RC=05("do not honor"). Add it tolegacyCodesmapped to a newErrDeclined; no caller changes.Swap the provider. Write a
StripeLikeACLwith the samePaymentGatewayport;mainchanges one constructor line.Decorate the ACL. Wrap
gwin a logging decorator from Lab 1's style (PaymentGatewayin,PaymentGatewayout). Expected: the ACL is now Adapter + Facade, decorated: three patterns, one call site.Laravel version. Bind
PaymentGatewayPorttoLegacyPayGatewayand run the commented test withHttp::fake.
<?php
// Lab: an anti-corruption layer for a legacy payment API.
// Domain side: Money, ChargeResult, domain exceptions. Legacy side: form posts,
// zero-padded amounts, two-digit response codes. Only this namespace knows both.
namespace App\Payments;
final readonly class Money
{
public function __construct(public int $minor, public string $currency) {}
}
final readonly class ChargeResult
{
public function __construct(public string $paymentId, public bool $approved) {}
}
class PaymentDeclined extends \DomainException {}
final class InsufficientFunds extends PaymentDeclined {}
final class CardBlocked extends PaymentDeclined {}
final class ProviderUnavailable extends \RuntimeException {}
interface PaymentGatewayPort
{
public function charge(string $orderId, Money $amount): ChargeResult;
}
namespace App\Payments\LegacyPay;
use App\Payments\CardBlocked;
use App\Payments\ChargeResult;
use App\Payments\InsufficientFunds;
use App\Payments\Money;
use App\Payments\PaymentGatewayPort;
use App\Payments\ProviderUnavailable;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Http;
use UnexpectedValueException;
/** Translator: the only place that knows the legacy vocabulary. */
final class LegacyPayTranslator
{
/** @return array<string, string> */
public function toLegacy(string $merchantId, string $orderId, Money $m): array
{
return [
'MERCHANT_ID' => $merchantId,
'AMT' => str_pad((string) $m->minor, 12, '0', STR_PAD_LEFT),
'CUR' => $m->currency,
'REF' => strtoupper($orderId),
];
}
public function fromLegacy(string $body): ChargeResult
{
parse_str(str_replace(';', '&', trim($body)), $kv);
return match ($kv['RC'] ?? null) {
'00' => new ChargeResult('pay_'.$kv['TXN'], true),
'51' => throw new InsufficientFunds,
'62' => throw new CardBlocked,
'91' => throw new ProviderUnavailable('legacy switch down'),
default => throw new UnexpectedValueException('unknown legacy code '.($kv['RC'] ?? 'none')),
};
}
}
/** Adapter + facade: implements our port with one call. */
final class LegacyPayGateway implements PaymentGatewayPort
{
public function __construct(
private LegacyPayTranslator $translator,
private string $baseUrl,
private string $merchantId,
) {}
public function charge(string $orderId, Money $amount): ChargeResult
{
try {
$response = Http::asForm()
->timeout(5)
->post($this->baseUrl.'/cgi-bin/pay.exe', $this->translator->toLegacy($this->merchantId, $orderId, $amount));
} catch (ConnectionException $e) {
throw new ProviderUnavailable($e->getMessage(), previous: $e);
}
return $this->translator->fromLegacy($response->body());
}
}
// Wiring (a service provider): the rest of the app sees only PaymentGatewayPort.
// $this->app->singleton(PaymentGatewayPort::class, fn () => new LegacyPayGateway(
// new LegacyPayTranslator, config('services.legacypay.url'), config('services.legacypay.merchant'),
// ));
//
// Test (no network):
// Http::fake(['*/cgi-bin/pay.exe' => Http::response('RC=51;MSG=INSUFF FUNDS;TXN=0')]);
// expect(fn () => app(PaymentGatewayPort::class)->charge('ord-2', new Money(9_000_000, 'IRR')))
// ->toThrow(InsufficientFunds::class);Lab 3 (optional): measure wrapping
go test -bench . -benchmem ./bench
# BenchmarkDirect-10 1000000000 0.2434 ns/op 0 B/op 0 allocs/op
# BenchmarkInterface-10 1000000000 0.2539 ns/op 0 B/op 0 allocs/op
# BenchmarkChain5-10 334184730 3.560 ns/op 0 B/op 0 allocs/op
# BenchmarkBuildChainPerCall-10 36539690 35.08 ns/op 80 B/op 5 allocs/op// Package bench measures what wrapping costs in Go: a direct call, a call
// through an interface, and a call through a chain of decorators.
// Run: go test -bench . -benchmem ./bench
package bench
import "testing"
type Pricer interface{ Price(qty int) int }
type base struct{ unit int }
func (b base) Price(q int) int { return b.unit * q }
// decorator: same interface, adds one responsibility (here: a tiny fee).
type fee struct{ next Pricer }
func (f fee) Price(q int) int { return f.next.Price(q) + 1 }
var sink int
func BenchmarkDirect(b *testing.B) {
p := base{unit: 3}
for i := range b.N {
sink = p.Price(i)
}
}
func BenchmarkInterface(b *testing.B) {
var p Pricer = base{unit: 3}
for i := range b.N {
sink = p.Price(i)
}
}
func BenchmarkChain5(b *testing.B) {
var p Pricer = base{unit: 3}
for range 5 {
p = fee{next: p}
}
for i := range b.N {
sink = p.Price(i)
}
}
// Building the chain on every call (e.g. per request) allocates.
func BenchmarkBuildChainPerCall(b *testing.B) {
for i := range b.N {
var p Pricer = base{unit: 3}
for range 5 {
p = &fee{next: p}
}
sink = p.Price(i)
}
}Common misconceptions
| Belief | Reality |
|---|---|
| Laravel facades are the GoF Facade | They are "static proxies" to one container binding; a GoF facade simplifies a subsystem |
| A facade must hide the subsystem completely | GoF: it does not prevent direct use of subsystem classes; use internal/ or module rules for a wall |
| Adapter, Decorator and Proxy are the same | Same structure, different intents: change interface / add stackable behaviour / control access |
| Bridge is a fancy Adapter | Adapter fixes a mismatch after the fact; Bridge separates two dimensions up front |
| Any wrapper around an API is an adapter | Only if it implements your interface and translates; exposing vendor types is not adapting |
| Composite means "a tree" | It means leaves and containers share one interface so clients do not branch |
| Decorator order does not matter | It decides what is logged, retried, measured and short-circuited |
| A caching proxy is free speed | It buys latency with staleness and an invalidation problem |
| Flyweight is a cache | It shares immutable intrinsic state to save memory; it does not store results |
| Wrappers are slow in Go | Measured: about 0.7 ns per interface layer; allocation only if you build chains per call |
| Embedding forwards everything | Only the static type's methods; optional interfaces like http.Flusher are hidden without Unwrap |
| Lazy loading is always good | It hides cost; in loops it becomes N+1 |
| An ACL is just an adapter | It is adapter + facade + translator, guarding a whole model, at a service boundary |
| Middleware is only Chain of Responsibility | Structurally it is Decorator; behaviourally it can short-circuit like CoR |
Cheat sheet
| Topic | Remember |
|---|---|
| Facade | New, simpler interface over many classes; does not forbid direct use |
| Adapter | Existing interface converted to the one clients expect; object form preferred |
| Composite | Leaf and container share one interface; transparency vs safety for Add |
| Proxy | Same interface, controls access: remote, virtual, protection, smart reference, caching |
| Decorator | Same interface, adds one responsibility, stackable; order matters |
| Bridge | Abstraction × implementor, connected by reference; designed up front |
| Flyweight | Intrinsic (shared, immutable) vs extrinsic (passed in) state |
| Laravel facades | Static proxies via __callStatic + getFacadeAccessor; mock with shouldReceive |
Container::extend | Laravel's decorator hook; last registered is outermost |
| Go decorators | bufio, gzip, TeeReader, middleware; flush/close outside-in |
Unwrap | Give ResponseWriter wrappers Unwrap() so ResponseController reaches Flush/Hijack |
RoundTripper | Do not interpret responses or mutate requests there; retry on a Doer above the client |
| Retry decorator | GetBody, drain+close, honour ctx, only idempotent requests |
| Gateway / ACL / sidecar | Facade+Proxy / Adapter+Facade / out-of-process Proxy |
| Performance | Build chains once; per-call wrapping allocates |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What does GoF say distinguishes a Facade from an Adapter? Must-know
Answer
Answer: A facade "defines a new interface, whereas an adapter reuses an old interface": the adapter makes an existing interface (the one the client expects) work with an incompatible class. See Telling the wrappers apart.
2 — Is Cache::get('k') in Laravel an example of the GoF Facade pattern? What is it? Must-know
Answer
Answer: No. It is a static proxy: Facade::__callStatic resolves the cache binding from the container and forwards the call. In GoF terms a Proxy reached through a Service Locator. See Laravel facades are static proxies.
3 — You wrap http.ResponseWriter to record the status code and server-sent events stop streaming. Why, and what is the fix? Important
Answer
Answer: The wrapper hides the optional http.Flusher interface of the original writer. Add Unwrap() http.ResponseWriter and use http.NewResponseController(w).Flush(), or forward Flush explicitly. See Lost optional interfaces.
4 — A retry decorator works for GET, but POST retries reach the server with an empty body. What went wrong? Important
Answer
Answer: The first attempt consumed the body and nothing could rewind it: Request.GetBody was nil (the body type was one http.NewRequest does not recognise) or the decorator did not use it. Re-create the body with GetBody for each attempt and refuse to retry when it is nil. It must also drain/close failed responses, honour ctx, and only replay idempotent requests. See The RoundTripper contract and Lab 1.
5 — Where do logging decorators go relative to retry if you want one log line per user-visible call? And to see dependency flakiness? Important
Answer
Answer: Outside retry for one line per logical call; inside retry for one line per attempt. See Order of decorators and Lab 1.
6 — Name GoF's four kinds of proxy and one modern example of each. Good to know
Answer
Answer: Remote (gRPC stub, httputil.ReverseProxy), virtual (sync.OnceValues, PHP 8.4 newLazyProxy), protection (an authorization wrapper), smart reference (reference counting, caching, copy-on-write). See Proxy.
7 — Three notification kinds and four channels: how many classes with subclassing, how many with Bridge? Must-know
Answer
Answer: 3 × 4 = 12 with one subclass per combination; 3 + 4 = 7 with Bridge. See Bridge.
8 — What is the difference between intrinsic and extrinsic state, and which one must be immutable? Important
Answer
Answer: Intrinsic state is context-independent and stored in the shared flyweight; it must be immutable. Extrinsic state depends on context and is kept by the client and passed in. See Flyweight.
9 — In Composite, what does GoF mean by "transparency vs safety"? Good to know
Answer
Answer: Putting child-management methods on the Component gives transparency (uniform treatment) but lets clients call Add on leaves; putting them only on the Composite gives safety but leaves and composites then differ. See Composite.
10 — Which two or three patterns make up an API gateway, an anti-corruption layer and a sidecar? Important
Answer
Answer: API gateway: Facade + Proxy. ACL: Adapter + Facade (+ a translator). Sidecar: an out-of-process Proxy that often acts as a Decorator. See Microservices.
11 — Why is Eloquent's lazy loading dangerous in a loop, and what does Laravel offer against it? Must-know
Answer
Answer: Each first access runs a query, so a loop over N models runs N+1 queries. Eager-load with with() and enable Model::preventLazyLoading() outside production. See Proxy and Lazy loading and N+1.
12 — What does building a five-layer decorator chain on every call cost in Go, compared with building it once? Important
Answer
Answer: In our benchmark about 35 ns, 80 B and 5 allocations per call, versus about 3.6 ns and zero allocations when the chain is built once. See Performance.
Glossary
| Term | Meaning |
|---|---|
| Structural pattern | GoF family about composing classes and objects into larger structures |
| Class pattern / object pattern | Structure via inheritance / via object composition |
| Composition over inheritance | Build behaviour by holding objects rather than extending classes |
| Facade | A new, higher-level interface over a subsystem |
| Subsystem | The set of classes a facade fronts |
| Adapter (Wrapper) | Converts an existing interface into the one a client expects |
| Target / Adaptee | The interface the client wants / the class being adapted |
| Class adapter / object adapter | Adapter by inheritance / by holding a reference |
| Two-way adapter | Implements both interfaces so both sides can use it |
| Composite | Tree where leaves and containers share an interface |
| Component / Leaf / Composite (participant) | The shared interface / an end node / a node with children |
| Transparency vs safety | Where child-management methods live in a Composite, and the trade-off |
| Proxy | A surrogate with the same interface that controls access to a subject |
| Subject / RealSubject | The shared interface / the real object behind the proxy |
| Remote proxy | Local representative of an object in another address space |
| Virtual proxy | Creates the expensive object on demand |
| Protection proxy | Checks access rights before forwarding |
| Smart reference | A proxy that adds actions on access (counting, locking, loading) |
| Caching proxy | A proxy that stores results to avoid calling the subject |
| Copy-on-write | Share until someone writes, then copy (GoF: a proxy optimisation) |
| Lazy Load | Fowler's pattern: load data on first access (Eloquent relationships) |
| Lazy ghost / lazy proxy | PHP 8.4 lazy objects: initialised in place / forwarding to a real instance |
| Decorator | Same interface, adds a responsibility, stackable |
| Middleware | A decorator around a request handler (PSR-15, Laravel, Go func(Handler) Handler) |
| Chain of Responsibility | Behavioural pattern: pass a request along a chain; any link may handle and stop it |
| Bridge | Abstraction and implementor hierarchies connected by a reference |
| Abstraction / Implementor | Client-facing side / platform-specific side of a Bridge |
| Flyweight | Shared object holding intrinsic state |
| Intrinsic / extrinsic state | Shared and context-free / context-dependent and passed in |
| Interning | Keeping one canonical copy of equal values (unique.Make) |
| Static proxy (Laravel) | Laravel's name for its facades: static calls forwarded to a container service |
| Real-time facade | A Laravel facade generated by importing Facades\Your\Class |
getFacadeAccessor | Method returning the container key behind a Laravel facade |
__callStatic / __call | PHP magic methods that forward unknown static / instance calls |
Container::extend | Laravel hook to decorate a resolved service |
| Service Locator | Getting dependencies by asking a registry (what Laravel facades do underneath) |
Unwrap | Method returning the wrapped value (errors, ResponseWriter) |
http.ResponseController | Go 1.20 helper that reaches Flush/Hijack through wrappers via Unwrap |
RoundTripper | Go interface for executing one HTTP transaction; a client decorator point with rules |
httputil.ReverseProxy | Go's reverse proxy handler; configure with Rewrite (not the deprecated Director) |
| Devirtualization | Compiler turning an interface call into a direct call when it knows the type |
| Anti-corruption layer (ACL) | Adapter + facade + translator protecting one model from another |
| API gateway | Single entry point: facade (aggregation) + proxy (routing, offloading) |
| Sidecar | A helper process deployed next to each instance; usually a proxy (Envoy) |
| Circuit breaker | A decorator that stops calling a failing dependency for a while |
| PSR-7 / PSR-15 / PSR-18 | PHP standards for HTTP messages / server middleware / HTTP clients |
| Flysystem | PHP filesystem abstraction with adapters for local, FTP, SFTP, S3 and more |
| Octane | Laravel's long-lived worker server; static state lives across requests |
References
- E. Gamma, R. Helm, R. Johnson, J. Vlissides, Design Patterns: Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Chapter 4. Course copy (UNC): Structural Patterns intro, Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy, Discussion of Structural Patterns
- Refactoring.Guru: Facade, Adapter, Composite, Proxy, Decorator, Bridge, Flyweight
- Go packages: io, bufio, compress/gzip, net/http (
HandlerFunc,RoundTripper,ResponseController,MaxBytesHandler), net/http/httputil (ReverseProxy,Rewrite), sync (OnceValues), unique - Go blog, New unique package
- Laravel 13: Facades, Service Container (
extend), Middleware, Cache (custom drivers,flexible), File Storage (Flysystem, custom filesystems), HTTP Client (retries, Guzzle middleware, macros), Notifications (custom channels), Eloquent Relationships (lazy loading), Eloquent, Validation - Laravel framework source (13.x): Facade.php, Container.php, PendingRequest.php, Macroable.php
- Guzzle, Handlers and Middleware
- PHP-FIG: PSR-7, PSR-15, PSR-18
- Flysystem documentation
- PHP manual: Lazy Objects, Enumerations basics
- Microsoft Azure Architecture Center: Anti-corruption Layer pattern, Sidecar pattern, API gateways
- Envoy, What is Envoy