Programming Search⌘K

Conceptcore

Structural pattern

Also called structural patterns, structural design pattern, class structural pattern, object structural pattern, wrapper pattern.

A structural pattern is a design pattern about how classes and objects are composed into larger structures. Most of them wrap one object in another and differ in what the wrapper does.

Applies to
core-languages

Idea

A program is rarely one class. Classes and objects are put together into larger structures, and the way they are put together decides what can change later. Wikipedia describes a structural pattern as a design pattern that encapsulates relationships between entities.1 Design Patterns says that structural patterns are concerned with how classes and objects are composed to form larger structures.2

Many structural patterns have the same shape: one object holds another and forwards calls to it. They differ in the interface that the outer object gives and in what it does with each call. Here are three wrappers around one sensor:

class Sensor:
    def __init__(self):
        self.reads = 0

    def read(self):
        self.reads += 1
        return 20  # degrees Celsius


class FahrenheitAdapter:  # a different interface
    def __init__(self, sensor):
        self.sensor = sensor

    def fahrenheit(self):
        return self.sensor.read() * 9 // 5 + 32


class Calibrated:  # the same interface, and one more responsibility
    def __init__(self, sensor, offset):
        self.sensor = sensor
        self.offset = offset

    def read(self):
        return self.sensor.read() + self.offset


class CachingProxy:  # the same interface, and control of access
    def __init__(self, sensor):
        self.sensor = sensor
        self.value = None

    def read(self):
        if self.value is None:
            self.value = self.sensor.read()
        return self.value


print(f"adapter: {FahrenheitAdapter(Sensor()).fahrenheit()} F")
print(f"decorator: {Calibrated(Sensor(), 1).read()}")
real = Sensor()
proxy = CachingProxy(real)
print(f"proxy: {proxy.read()} {proxy.read()}, real reads: {real.reads}")
Output
adapter: 68 F
decorator: 21
proxy: 20 20, real reads: 1

The adapter changes the interface. The decorator keeps the interface and adds a calibration. The proxy keeps the interface and decides when the real sensor is read. The code that each wrapper contains is almost the same, so the name of the pattern is mostly a statement of intent.

How it works

Class and object structural patterns. Design Patterns classifies its patterns by purpose and by scope.2 A structural class pattern uses inheritance to compose interfaces or implementations. A structural object pattern composes objects at run time to get new functionality, so the composition can change while the program runs. Adapter is the only structural pattern of the book with both forms: a class adapter inherits from the adaptee, and an object adapter holds it. Bridge, Composite, Decorator, Facade, Flyweight and Proxy are object patterns.2

Wrappers compared. Most of the seven patterns hold a reference to another object. The table shows what each one changes:2

Pattern Interface to the client What the pattern does
Adapter pattern the one the client expects, not the one of the wrapped object makes existing classes work together after they are designed
Bridge pattern an abstraction with its own hierarchy separates an abstraction from its implementation up front, so that both can vary
Decorator pattern the same as the wrapped object adds responsibilities to one object, and wrappers can be stacked
Proxy pattern the same as the wrapped object a placeholder that controls access to the real object
Composite pattern the same for a leaf and for a group puts objects in a tree, so that clients treat one object and a group in the same way
Facade pattern a new, simpler interface gives one interface to a set of classes in a subsystem
Flyweight pattern the same as an unshared object shares objects to support large numbers of fine-grained objects

Decorator and Proxy have the same structure, so their difference is the purpose. A decorator adds behaviour, and it is often stacked. A proxy is a stand-in for an object that is inconvenient or undesirable to access directly.2

Other structural patterns. Wikipedia also lists the marker interface, the opaque pointer and pipes and filters as structural patterns.1 This area adds patterns from other sources: Delegation pattern, Mixin, Module pattern, Private class data, Marker interface, Twin, Whole-Part and Extension object.

Languages change the patterns. Peter Norvig found that 16 of the 23 patterns of Design Patterns are invisible or simpler in Dylan or Lisp. Among the structural patterns, first-class types make Flyweight and Proxy simpler, and modules make Facade invisible: a module exports only the names that make up the interface.3 Some languages also generate the forwarding code of a wrapper, which is the part that is the same in all of them.

In languages

LanguageVerdictNote
PythonIdiom
C++Idiom
JavaIdiom
CIdiomAn opaque pointer hides a struct behind functions, and a struct of function pointers is an interface that a wrapper can implement and forward.
C#Idiom
JavaScriptNative
TypeScriptIdiom
GoNative
RustIdiom
KotlinNativeClass delegation with by makes the compiler generate the methods of an interface that forward to a stored object, so a decorator declares only the methods that it changes; no example is executed here because the test image has no kotlinc.
SQLIdiomA view gives a simpler or a changed interface to one or more tables, which is the role of a facade or an adapter.
BashIdiomA pipeline joins filters, and a function with the name of a command can wrap the command and forward its arguments.
PowerShellIdiomThe pipeline joins commands, and a class can implement an interface and wrap a .NET object; no example is executed here because the test image has no pwsh.
HTMLDoes not applyElements nest, but markup has no objects or interfaces to compose.
CSSDoes not applyStyle rules have no objects or interfaces to compose.
Regular expressionsDoes not applyA pattern has no objects to compose.
Language Verdict Mechanism
Python idiom duck typing, so a wrapper needs only the methods that are called; __getattr__ to forward the rest; modules as facades
JavaScript native the Proxy object intercepts the operations on another object; duck typing; modules
TypeScript idiom interfaces for the wrapped and the wrapper type; Proxy from JavaScript
Java idiom interfaces and object composition; java.lang.reflect.Proxy for dynamic proxies; stream classes that wrap other streams
Kotlin native class delegation with by, where the compiler generates the forwarding methods
C# idiom interfaces and object composition; stream classes that wrap other streams
Go native struct embedding promotes the methods of the embedded field; small interfaces such as io.Reader
Rust idiom traits and wrapper structs; Deref for smart pointers
C idiom opaque pointers; structs of function pointers as interfaces
C++ idiom virtual functions and composition; multiple inheritance for a class adapter; smart pointers as proxies
Bash idiom a pipeline joins filters; a function wraps a command
PowerShell idiom the pipeline; classes that implement interfaces and wrap .NET objects
SQL idiom a view gives a simpler or a changed interface to tables
Regex n/a a pattern has no objects to compose
HTML n/a elements nest, but markup has no objects or interfaces
CSS n/a style rules have no objects or interfaces

Three languages generate the forwarding. In Go, a field or method of an embedded field is promoted, and the method set of the struct includes the promoted methods.4 A struct that embeds a value and declares one method of its own is a decorator with no forwarding code. In Kotlin, the by-clause in the supertype list "indicates that b will be stored internally in objects of Derived and the compiler will generate all the methods of Base that forward to b."5 In JavaScript, a Proxy object can intercept and redefine fundamental operations for another object.6

Python forwards by a hook: __getattr__ is called when the default attribute access fails.7 Rust uses Deref for types that act like a value of another type, which are often called smart pointers. A type that implements Deref<Target = U> implicitly implements all the methods of U that take &self.8 The documentation advises against Deref for a type with methods that are likely to collide with methods of the target type, so it is not a general tool for decorators.8

The example files show the three wrappers of the Idea section in each language. Python forwards with __getattr__. JavaScript uses a Proxy for the proxy. TypeScript, Java, C# and C++ use an interface or an abstract class. Go embeds the sensor in the decorator. Rust uses a trait.

PythonGitHub
class Sensor:
    def __init__(self):
        self.reads = 0

    def read(self):
        self.reads += 1
        return 20

    def unit(self):
        return "C"


class FahrenheitAdapter:
    def __init__(self, sensor):
        self._sensor = sensor

    def fahrenheit(self):
        return self._sensor.read() * 9 // 5 + 32


class Calibrated:
    """A decorator: it overrides read and forwards every other attribute."""

    def __init__(self, sensor, offset):
        self._sensor = sensor
        self._offset = offset

    def read(self):
        return self._sensor.read() + self._offset

    def __getattr__(self, name):  # called only when normal lookup fails
        return getattr(self._sensor, name)


class CachingProxy:
    def __init__(self, sensor):
        self._sensor = sensor
        self._value = None

    def read(self):
        if self._value is None:
            self._value = self._sensor.read()
        return self._value

    def __getattr__(self, name):
        return getattr(self._sensor, name)


print(f"adapter: {FahrenheitAdapter(Sensor()).fahrenheit()} F")
calibrated = Calibrated(Sensor(), 1)
assert calibrated.unit() == "C"  # forwarded by __getattr__
print(f"decorator: {calibrated.read()}")
real = Sensor()
proxy = CachingProxy(real)
print(f"proxy: {proxy.read()} {proxy.read()}, real reads: {real.reads}")
Output
adapter: 68 F
decorator: 21
proxy: 20 20, real reads: 1
  • Verdict: idiom. Duck typing means that a wrapper needs only the methods that clients call, and __getattr__ forwards the rest. Special methods such as __len__ must be defined on the wrapper class.
#include <iostream>
#include <optional>

struct Thermometer {
    virtual ~Thermometer() = default;
    virtual int read() = 0;
};

struct Sensor : Thermometer {
    int reads = 0;
    int read() override {
        ++reads;
        return 20;
    }
};

class FahrenheitAdapter {
public:
    explicit FahrenheitAdapter(Thermometer& sensor) : sensor_(sensor) {}
    int fahrenheit() { return sensor_.read() * 9 / 5 + 32; }

private:
    Thermometer& sensor_;
};

class Calibrated : public Thermometer {
public:
    Calibrated(Thermometer& sensor, int offset) : sensor_(sensor), offset_(offset) {}
    int read() override { return sensor_.read() + offset_; }

private:
    Thermometer& sensor_;
    int offset_;
};

class CachingProxy : public Thermometer {
public:
    explicit CachingProxy(Thermometer& sensor) : sensor_(sensor) {}
    int read() override {
        if (!value_) value_ = sensor_.read();
        return *value_;
    }

private:
    Thermometer& sensor_;
    std::optional<int> value_;
};

int main() {
    Sensor a, b, real;
    std::cout << "adapter: " << FahrenheitAdapter(a).fahrenheit() << " F\n";
    std::cout << "decorator: " << Calibrated(b, 1).read() << "\n";
    CachingProxy proxy(real);
    int first = proxy.read();
    int second = proxy.read();
    std::cout << "proxy: " << first << " " << second << ", real reads: " << real.reads << "\n";
}
Output
adapter: 68 F
decorator: 21
proxy: 20 20, real reads: 1
  • Verdict: idiom. The decorator and the proxy derive from the abstract class and hold a reference to the sensor. The two reads of the proxy are in separate statements, so their order is clear.
JavaGitHub
interface Thermometer { int read(); }

class Sensor implements Thermometer {
    int reads;
    public int read() { reads++; return 20; }
}

class FahrenheitAdapter {
    private final Thermometer sensor;
    FahrenheitAdapter(Thermometer sensor) { this.sensor = sensor; }
    int fahrenheit() { return sensor.read() * 9 / 5 + 32; }
}

class Calibrated implements Thermometer {
    private final Thermometer sensor;
    private final int offset;
    Calibrated(Thermometer sensor, int offset) { this.sensor = sensor; this.offset = offset; }
    public int read() { return sensor.read() + offset; }
}

class CachingProxy implements Thermometer {
    private final Thermometer sensor;
    private Integer value;
    CachingProxy(Thermometer sensor) { this.sensor = sensor; }
    public int read() {
        if (value == null) value = sensor.read();
        return value;
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println("adapter: " + new FahrenheitAdapter(new Sensor()).fahrenheit() + " F");
        System.out.println("decorator: " + new Calibrated(new Sensor(), 1).read());
        Sensor real = new Sensor();
        Thermometer proxy = new CachingProxy(real);
        System.out.println("proxy: " + proxy.read() + " " + proxy.read() + ", real reads: " + real.reads);
    }
}
Output
adapter: 68 F
decorator: 21
proxy: 20 20, real reads: 1
  • Verdict: idiom. Each wrapper is a class that holds the sensor; the decorator and the proxy implement the same interface. java.lang.reflect.Proxy can generate a proxy class at run time for a list of interfaces.
using System;

interface IThermometer { int Read(); }

class Sensor : IThermometer
{
    public int Reads;
    public int Read() { Reads++; return 20; }
}

class FahrenheitAdapter
{
    private readonly IThermometer sensor;
    public FahrenheitAdapter(IThermometer sensor) { this.sensor = sensor; }
    public int Fahrenheit() => sensor.Read() * 9 / 5 + 32;
}

class Calibrated : IThermometer
{
    private readonly IThermometer sensor;
    private readonly int offset;
    public Calibrated(IThermometer sensor, int offset) { this.sensor = sensor; this.offset = offset; }
    public int Read() => sensor.Read() + offset;
}

class CachingProxy : IThermometer
{
    private readonly Lazy<int> value;
    public CachingProxy(IThermometer sensor) { value = new Lazy<int>(sensor.Read); }
    public int Read() => value.Value;
}

class Program
{
    static void Main()
    {
        Console.WriteLine($"adapter: {new FahrenheitAdapter(new Sensor()).Fahrenheit()} F");
        Console.WriteLine($"decorator: {new Calibrated(new Sensor(), 1).Read()}");
        var real = new Sensor();
        IThermometer proxy = new CachingProxy(real);
        Console.WriteLine($"proxy: {proxy.Read()} {proxy.Read()}, real reads: {real.Reads}");
    }
}
Output
adapter: 68 F
decorator: 21
proxy: 20 20, real reads: 1
  • Verdict: idiom. The wrappers are classes that implement the interface of the sensor. Lazy<T> holds the one real read of the proxy.
JavaScriptGitHub
class Sensor {
  reads = 0;
  read() {
    this.reads += 1;
    return 20;
  }
}

class FahrenheitAdapter {
  constructor(sensor) {
    this.sensor = sensor;
  }
  fahrenheit() {
    return Math.floor((this.sensor.read() * 9) / 5) + 32;
  }
}

class Calibrated {
  constructor(sensor, offset) {
    this.sensor = sensor;
    this.offset = offset;
  }
  read() {
    return this.sensor.read() + this.offset;
  }
}

// The proxy: a Proxy object intercepts the property access "read".
function cachingProxy(sensor) {
  let value;
  return new Proxy(sensor, {
    get(target, prop, receiver) {
      if (prop === "read") {
        return () => (value ??= target.read());
      }
      return Reflect.get(target, prop, receiver);
    },
  });
}

console.log(`adapter: ${new FahrenheitAdapter(new Sensor()).fahrenheit()} F`);
console.log(`decorator: ${new Calibrated(new Sensor(), 1).read()}`);
const real = new Sensor();
const proxy = cachingProxy(real);
console.log(`proxy: ${proxy.read()} ${proxy.read()}, real reads: ${proxy.reads}`);
Output
adapter: 68 F
decorator: 21
proxy: 20 20, real reads: 1
  • Verdict: native. The Proxy object intercepts operations on another object, so a proxy needs code only for the operations that it changes. Reflect.get forwards the rest, here reads.
TypeScriptGitHub
interface Thermometer {
  read(): number;
}

class Sensor implements Thermometer {
  reads = 0;
  read(): number {
    this.reads += 1;
    return 20;
  }
}

class FahrenheitAdapter {
  private readonly sensor: Thermometer;
  constructor(sensor: Thermometer) {
    this.sensor = sensor;
  }
  fahrenheit(): number {
    return Math.floor((this.sensor.read() * 9) / 5) + 32;
  }
}

class Calibrated implements Thermometer {
  private readonly sensor: Thermometer;
  private readonly offset: number;
  constructor(sensor: Thermometer, offset: number) {
    this.sensor = sensor;
    this.offset = offset;
  }
  read(): number {
    return this.sensor.read() + this.offset;
  }
}

class CachingProxy implements Thermometer {
  private readonly sensor: Thermometer;
  private value: number | undefined;
  constructor(sensor: Thermometer) {
    this.sensor = sensor;
  }
  read(): number {
    this.value ??= this.sensor.read();
    return this.value;
  }
}

function show(t: Thermometer): number {
  return t.read(); // the client knows only the interface
}

console.log(`adapter: ${new FahrenheitAdapter(new Sensor()).fahrenheit()} F`);
console.log(`decorator: ${show(new Calibrated(new Sensor(), 1))}`);
const real = new Sensor();
const proxy = new CachingProxy(real);
console.log(`proxy: ${show(proxy)} ${show(proxy)}, real reads: ${real.reads}`);
Output
adapter: 68 F
decorator: 21
proxy: 20 20, real reads: 1
  • Verdict: idiom. An interface names what the decorator and the proxy share with the sensor, and the compiler checks that each wrapper implements it.
package main

import "fmt"

type Thermometer interface{ Read() int }

type Sensor struct{ reads int }

func (s *Sensor) Read() int { s.reads++; return 20 }
func (s *Sensor) Unit() string { return "C" }

type FahrenheitAdapter struct{ sensor Thermometer }

func (a FahrenheitAdapter) Fahrenheit() int { return a.sensor.Read()*9/5 + 32 }

// Calibrated embeds *Sensor: Unit is promoted, and Read is replaced.
type Calibrated struct {
	*Sensor
	offset int
}

func (c Calibrated) Read() int { return c.Sensor.Read() + c.offset }

type CachingProxy struct {
	sensor Thermometer
	value  *int
}

func (p *CachingProxy) Read() int {
	if p.value == nil {
		v := p.sensor.Read()
		p.value = &v
	}
	return *p.value
}

func main() {
	fmt.Printf("adapter: %d F\n", FahrenheitAdapter{&Sensor{}}.Fahrenheit())
	c := Calibrated{&Sensor{}, 1}
	_ = c.Unit() // promoted from the embedded *Sensor
	fmt.Printf("decorator: %d\n", c.Read())
	real := &Sensor{}
	var proxy Thermometer = &CachingProxy{sensor: real}
	first, second := proxy.Read(), proxy.Read()
	fmt.Printf("proxy: %d %d, real reads: %d\n", first, second, real.reads)
}
Output
adapter: 68 F
decorator: 21
proxy: 20 20, real reads: 1
  • Verdict: native. Struct embedding promotes the methods of the embedded field, so the decorator declares only the method that it changes. The interface Thermometer is satisfied without a declaration.
RustGitHub
use std::cell::{Cell, OnceCell};

trait Thermometer {
    fn read(&self) -> i32;
}

struct Sensor {
    reads: Cell<u32>,
}

impl Thermometer for Sensor {
    fn read(&self) -> i32 {
        self.reads.set(self.reads.get() + 1);
        20
    }
}

struct FahrenheitAdapter<T: Thermometer>(T);

impl<T: Thermometer> FahrenheitAdapter<T> {
    fn fahrenheit(&self) -> i32 {
        self.0.read() * 9 / 5 + 32
    }
}

struct Calibrated<T: Thermometer> {
    inner: T,
    offset: i32,
}

impl<T: Thermometer> Thermometer for Calibrated<T> {
    fn read(&self) -> i32 {
        self.inner.read() + self.offset
    }
}

struct CachingProxy<'a, T: Thermometer> {
    inner: &'a T,
    value: OnceCell<i32>,
}

impl<T: Thermometer> Thermometer for CachingProxy<'_, T> {
    fn read(&self) -> i32 {
        *self.value.get_or_init(|| self.inner.read())
    }
}

fn sensor() -> Sensor {
    Sensor { reads: Cell::new(0) }
}

fn main() {
    println!("adapter: {} F", FahrenheitAdapter(sensor()).fahrenheit());
    println!("decorator: {}", Calibrated { inner: sensor(), offset: 1 }.read());
    let real = sensor();
    let proxy = CachingProxy { inner: &real, value: OnceCell::new() };
    let (first, second) = (proxy.read(), proxy.read());
    println!("proxy: {} {}, real reads: {}", first, second, real.reads.get());
}
Output
adapter: 68 F
decorator: 21
proxy: 20 20, real reads: 1
  • Verdict: idiom. Generic wrapper structs implement the same trait as the value they hold, and calls through a generic type parameter are dispatched statically. Deref is meant for smart pointers, not for decorators.
  • Class versus object composition. A class pattern fixes the structure when the program is compiled. An object pattern can change it at run time, which is one reason for the advice of Design Patterns to favor object composition over class inheritance.2 See Composition over inheritance.
  • Generated wrappers. Dynamic proxies, Proxy in JavaScript and Kotlin's by remove the forwarding code, and the wrapper holds only the behaviour that differs.
  • Structure without wrappers. A facade can be a module, a flyweight can be a cache of shared values, and a composite can be a recursive data type.
  • Creational and behavioral patterns. A structural pattern is about how parts fit together. A Creational pattern is about how objects are created, and a behavioral pattern is about algorithms and the assignment of responsibilities between objects.2

Pitfalls

  • Identity. A wrapper is a different object. A test of identity or a key in a map that holds the wrapped object does not find the wrapper.
  • Partial forwarding. A hand-written wrapper forwards only the methods that it declares. In Python, __getattr__ forwards normal attribute access, but implicit invocations of special methods use the type, not the instance, so len does not go through the hook:7

This code runs but gives a wrong answer on purpose.

class Logged:
    def __init__(self, inner):
        self._inner = inner

    def __getattr__(self, name):  # called only when normal lookup fails
        return getattr(self._inner, name)


items = Logged([3, 1, 2, 1])
print("count:", items.count(1))
try:
    print("len:", len(items))
except TypeError as e:
    print("len:", e)
Output
count: 2
len: object of type 'Logged' has no len()

The fix is to define each special method that the wrapper must support on the wrapper class, for example def __len__(self): return len(self._inner).

  • Deep stacks. Each layer of decorators or proxies is one more object to read through in a stack trace or a debugger.
  • The wrong pattern name. An adapter that also adds behaviour, or a proxy that changes the interface, confuses readers who know the names. Name the wrapper by what it does.

Cost

Each wrapper adds one call and one object. In most programs this is small next to the work of the wrapped object. A proxy or a flyweight can save more than it costs: a proxy can avoid the creation or the use of an expensive object, and a flyweight shares one object among many uses. In Rust and C++, a wrapper that the compiler sees in full can be inlined, while a wrapper behind a trait object or a virtual function is called through dynamic dispatch.

History

Design Patterns, by Gamma, Helm, Johnson and Vlissides, appeared in 1994. It classified 23 patterns by purpose and scope. Its structural group has seven patterns: Adapter, Bridge, Composite, Decorator, Facade, Flyweight and Proxy.2

Peter Norvig presented Design Patterns in Dynamic Programming at Object World on May 5, 1996. He listed Flyweight and Proxy among the six patterns that first-class types make invisible or simpler, and Facade as the pattern that modules make invisible.3 Later lists of structural patterns add patterns from other sources, such as the marker interface and the opaque pointer.1

References

  1. Structural pattern, Wikipedia, Introduction; Examples
  2. Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Chapter 1, Organizing the Catalog (Table 1.1); Chapter 4, Structural Patterns, introduction and Discussion of Structural Patterns
  3. Peter Norvig, Design Patterns in Dynamic Programming, Object World, May 5, 1996, slides 9 and 28
  4. The Go Programming Language Specification, Struct types, embedded fields and promoted methods
  5. Delegation, Kotlin documentation, Implementation by delegation
  6. Proxy, MDN Web Docs, Introduction
  7. Data model, The Python Language Reference, Python 3.14, 3.3.2.1 object.__getattr__; 3.3.13 Special method lookup
  8. Trait Deref, Rust standard library, Deref coercion; When to implement Deref or DerefMut

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/4NCWB4/text.yaml